blob: 89881f739fbb332a70f562279f1ae915b28d7bc4 [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"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000044#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000049#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000050#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000053#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000056#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000057#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000058#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000059#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000062#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000063#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000064#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000065using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000066using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000067
Chris Lattner0e5f4992006-12-19 21:40:18 +000068STATISTIC(NumCombined , "Number of insts combined");
69STATISTIC(NumConstProp, "Number of constant folds");
70STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000073
Chris Lattner0e5f4992006-12-19 21:40:18 +000074namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000075 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000079 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000081 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000082 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000084 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000085 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000086
Owen Anderson07cf79e2009-07-06 23:00:19 +000087 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000088
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000092 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000093 Worklist.push_back(I);
94 }
95
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
100
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
103
104 WorklistMap.erase(It);
105 }
106
107 Instruction *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113
Chris Lattnerdbab3862007-03-02 21:28:56 +0000114
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
117 /// now.
118 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000119 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000121 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000122 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 }
124
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
127 ///
128 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000131 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000132 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000133
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
137 ///
138 /// Return the specified operand before it is turned into an undef.
139 ///
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
142
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000145 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000146 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000147 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000148 }
149
150 return R;
151 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000152
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000154 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000155
156 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000157
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000159 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000160 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000161 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000162 }
163
Chris Lattner28977af2004-04-05 01:30:19 +0000164 TargetData &getTargetData() const { return *TD; }
165
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000170 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000171 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000172 //
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000211
Reid Spencere4d87aa2006-12-23 06:05:41 +0000212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000215 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000230 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000240 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000241 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000242 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000243 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000244 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000245 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000246 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000252 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000253
Chris Lattner9fe38862003-06-19 17:00:31 +0000254 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000255 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000256 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Chris Lattner9fe38862003-06-19 17:00:31 +0000263
Chris Lattner28977af2004-04-05 01:30:19 +0000264 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
Chris Lattner955f3312004-09-28 21:48:02 +0000268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000274 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000282 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000283
Chris Lattnere2ed0572006-04-06 19:19:17 +0000284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000286
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000288 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000289 return C;
290 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Chris Lattner0c967662004-09-24 15:21:34 +0000296
Chris Lattner8b170942002-08-09 23:47:40 +0000297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000304 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000312 return &I;
313 }
Chris Lattner8b170942002-08-09 23:47:40 +0000314 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000341 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000345 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng388df622009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Chris Lattner7da52b22006-11-01 04:51:18 +0000380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohman6de29f82009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000413 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
414 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000415 return 3;
416 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000417 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000420}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000421
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422// isOnlyUse - Return true if this instruction will be deleted if we stop using
423// it.
424static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000425 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426}
427
Chris Lattner4cb170c2004-02-23 06:38:22 +0000428// getPromotedType - Return the specified type promoted as it would be to pass
429// though a va_arg area...
430static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000434 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000435 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000436}
437
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000438/// getBitCastOperand - If the specified operand is a CastInst, a constant
439/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
440/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000441static Value *getBitCastOperand(Value *V) {
442 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000444 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000445 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
446 // GetElementPtrInst?
447 if (GEP->hasAllZeroIndices())
448 return GEP->getOperand(0);
449 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000450 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000451 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000452 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 else if (CE->getOpcode() == Instruction::GetElementPtr) {
454 // GetElementPtr ConstantExp?
455 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
456 I != E; ++I) {
457 ConstantInt *CI = dyn_cast<ConstantInt>(I);
458 if (!CI || !CI->isZero())
459 // Any non-zero indices? Not cast-like.
460 return 0;
461 }
462 // All-zero indices? This is just like casting.
463 return CE->getOperand(0);
464 }
465 }
Chris Lattnereed48272005-09-13 00:40:14 +0000466 return 0;
467}
468
Reid Spencer3da59db2006-11-27 01:05:10 +0000469/// This function is a wrapper around CastInst::isEliminableCastPair. It
470/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000471static Instruction::CastOps
472isEliminableCastPair(
473 const CastInst *CI, ///< The first cast instruction
474 unsigned opcode, ///< The opcode of the second cast instruction
475 const Type *DstTy, ///< The target type for the second cast instruction
476 TargetData *TD ///< The target data for pointer size
477) {
478
479 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
480 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000481
Reid Spencer3da59db2006-11-27 01:05:10 +0000482 // Get the opcodes of the two Cast instructions
483 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
484 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000485
Chris Lattnera0e69692009-03-24 18:35:40 +0000486 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487 DstTy, TD->getIntPtrType());
488
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
491 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
492 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
493 Res = 0;
494
495 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000496}
497
498/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
499/// in any code being generated. It does not require codegen if V is simple
500/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000501static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
502 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000503 if (V->getType() == Ty || isa<Constant>(V)) return false;
504
Chris Lattner01575b72006-05-25 23:24:33 +0000505 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000506 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000507 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000508 return false;
509 return true;
510}
511
Chris Lattner4f98c562003-03-10 21:43:22 +0000512// SimplifyCommutative - This performs a few simplifications for commutative
513// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000514//
Chris Lattner4f98c562003-03-10 21:43:22 +0000515// 1. Order operands such that they are listed from right (least complex) to
516// left (most complex). This puts constants before unary operators before
517// binary operators.
518//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
520// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000521//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 bool Changed = false;
524 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
525 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000526
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 if (!I.isAssociative()) return Changed;
528 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
530 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
531 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000532 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000533 cast<Constant>(I.getOperand(1)),
534 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 I.setOperand(0, Op->getOperand(0));
536 I.setOperand(1, Folded);
537 return true;
538 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
539 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
540 isOnlyUse(Op) && isOnlyUse(Op1)) {
541 Constant *C1 = cast<Constant>(Op->getOperand(1));
542 Constant *C2 = cast<Constant>(Op1->getOperand(1));
543
544 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000545 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000546 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547 Op1->getOperand(0),
548 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000549 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 I.setOperand(0, New);
551 I.setOperand(1, Folded);
552 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000553 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000556}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000557
Reid Spencere4d87aa2006-12-23 06:05:41 +0000558/// SimplifyCompare - For a CmpInst this function just orders the operands
559/// so that theyare listed from right (least complex) to left (most complex).
560/// This puts constants before unary operators before binary operators.
561bool InstCombiner::SimplifyCompare(CmpInst &I) {
562 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
563 return false;
564 I.swapOperands();
565 // Compare instructions are not associative so there's nothing else we can do.
566 return true;
567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
570// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000571//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000572static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000573 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000574 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000575
Chris Lattner0ce85802004-12-14 20:08:06 +0000576 // Constants can be considered to be negated values if they can be folded.
577 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000578 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000579
580 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
581 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000582 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000583
Chris Lattner8d969642003-03-10 23:06:50 +0000584 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000585}
586
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000587// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
588// instruction if the LHS is a constant negative zero (which is the 'negate'
589// form).
590//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000591static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000592 if (BinaryOperator::isFNeg(V))
593 return BinaryOperator::getFNegArgument(V);
594
595 // Constants can be considered to be negated values if they can be folded.
596 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000597 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000598
599 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
600 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000601 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000602
603 return 0;
604}
605
Owen Anderson07cf79e2009-07-06 23:00:19 +0000606static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000607 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000608 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000609
610 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000611 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000612 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000613 return 0;
614}
615
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616// dyn_castFoldableMul - If this value is a multiply that can be folded into
617// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000618// non-constant operand of the multiply, and set CST to point to the multiplier.
619// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620//
Owen Andersond672ecb2009-07-03 00:17:18 +0000621static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000622 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000623 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000624 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000625 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000626 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000627 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000628 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000630 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000631 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000632 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000633 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 return I->getOperand(0);
635 }
636 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000637 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000638}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000639
Chris Lattner574da9b2005-01-13 20:14:25 +0000640/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
641/// expression, return it.
642static User *dyn_castGetElementPtr(Value *V) {
643 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
644 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
645 if (CE->getOpcode() == Instruction::GetElementPtr)
646 return cast<User>(V);
647 return false;
648}
649
Dan Gohmaneee962e2008-04-10 18:43:06 +0000650/// getOpcode - If this is an Instruction or a ConstantExpr, return the
651/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000652static unsigned getOpcode(const Value *V) {
653 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000654 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000655 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000656 return CE->getOpcode();
657 // Use UserOp1 to mean there's no opcode.
658 return Instruction::UserOp1;
659}
660
Reid Spencer7177c3a2007-03-25 05:33:51 +0000661/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000662static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000663 return Context->getConstantExprAdd(C,
664 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000665}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000666/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000667static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000668 return Context->getConstantExprSub(C,
669 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000670}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000671/// MultiplyOverflows - True if the multiply can not be expressed in an int
672/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000673static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000674 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000675 uint32_t W = C1->getBitWidth();
676 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
677 if (sign) {
678 LHSExt.sext(W * 2);
679 RHSExt.sext(W * 2);
680 } else {
681 LHSExt.zext(W * 2);
682 RHSExt.zext(W * 2);
683 }
684
685 APInt MulExt = LHSExt * RHSExt;
686
687 if (sign) {
688 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
689 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
690 return MulExt.slt(Min) || MulExt.sgt(Max);
691 } else
692 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
693}
Chris Lattner955f3312004-09-28 21:48:02 +0000694
Reid Spencere7816b52007-03-08 01:52:58 +0000695
Chris Lattner255d8912006-02-11 09:31:47 +0000696/// ShrinkDemandedConstant - Check to see if the specified operand of the
697/// specified instruction is a constant integer. If so, check to see if there
698/// are any bits set in the constant that are not demanded. If so, shrink the
699/// constant and return true.
700static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000701 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000702 assert(I && "No instruction?");
703 assert(OpNo < I->getNumOperands() && "Operand index too large");
704
705 // If the operand is not a constant integer, nothing to do.
706 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
707 if (!OpC) return false;
708
709 // If there are no bits set that aren't demanded, nothing to do.
710 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
711 if ((~Demanded & OpC->getValue()) == 0)
712 return false;
713
714 // This instruction is producing bits that are not demanded. Shrink the RHS.
715 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000716 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000717 return true;
718}
719
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
721// set of known zero and one bits, compute the maximum and minimum values that
722// could have the specified known zero and known one bits, returning them in
723// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000724static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000725 const APInt& KnownOne,
726 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728 KnownZero.getBitWidth() == Min.getBitWidth() &&
729 KnownZero.getBitWidth() == Max.getBitWidth() &&
730 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000731 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000733 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
734 // bit if it is unknown.
735 Min = KnownOne;
736 Max = KnownOne|UnknownBits;
737
Dan Gohman1c8491e2009-04-25 17:12:48 +0000738 if (UnknownBits.isNegative()) { // Sign bit is unknown
739 Min.set(Min.getBitWidth()-1);
740 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000742}
743
744// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
745// a set of known zero and one bits, compute the maximum and minimum values that
746// could have the specified known zero and known one bits, returning them in
747// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000748static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000749 const APInt &KnownOne,
750 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000751 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
752 KnownZero.getBitWidth() == Min.getBitWidth() &&
753 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000754 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000755 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000756
757 // The minimum value is when the unknown bits are all zeros.
758 Min = KnownOne;
759 // The maximum value is when the unknown bits are all ones.
760 Max = KnownOne|UnknownBits;
761}
Chris Lattner255d8912006-02-11 09:31:47 +0000762
Chris Lattner886ab6c2009-01-31 08:15:18 +0000763/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
764/// SimplifyDemandedBits knows about. See if the instruction has any
765/// properties that allow us to simplify its operands.
766bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000767 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000768 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
769 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
770
771 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
772 KnownZero, KnownOne, 0);
773 if (V == 0) return false;
774 if (V == &Inst) return true;
775 ReplaceInstUsesWith(Inst, V);
776 return true;
777}
778
779/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
780/// specified instruction operand if possible, updating it in place. It returns
781/// true if it made any change and false otherwise.
782bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
783 APInt &KnownZero, APInt &KnownOne,
784 unsigned Depth) {
785 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
786 KnownZero, KnownOne, Depth);
787 if (NewVal == 0) return false;
788 U.set(NewVal);
789 return true;
790}
791
792
793/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
794/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000795/// that only the bits set in DemandedMask of the result of V are ever used
796/// downstream. Consequently, depending on the mask and V, it may be possible
797/// to replace V with a constant or one of its operands. In such cases, this
798/// function does the replacement and returns true. In all other cases, it
799/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000800/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000801/// to be zero in the expression. These are provided to potentially allow the
802/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
803/// the expression. KnownOne and KnownZero always follow the invariant that
804/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
805/// the bits in KnownOne and KnownZero may only be accurate for those bits set
806/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
807/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000808///
809/// This returns null if it did not change anything and it permits no
810/// simplification. This returns V itself if it did some simplification of V's
811/// operands based on the information about what bits are demanded. This returns
812/// some other non-null value if it found out that V is equal to another value
813/// in the context where the specified bits are demanded, but not for all users.
814Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
815 APInt &KnownZero, APInt &KnownOne,
816 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000817 assert(V != 0 && "Null pointer of Value???");
818 assert(Depth <= 6 && "Limit Search Depth");
819 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000820 const Type *VTy = V->getType();
821 assert((TD || !isa<PointerType>(VTy)) &&
822 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000823 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
824 (!VTy->isIntOrIntVector() ||
825 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000828 "Value *V, DemandedMask, KnownZero and KnownOne "
829 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
831 // We know all of the bits for a constant!
832 KnownOne = CI->getValue() & DemandedMask;
833 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000835 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000836 if (isa<ConstantPointerNull>(V)) {
837 // We know all of the bits for a constant!
838 KnownOne.clear();
839 KnownZero = DemandedMask;
840 return 0;
841 }
842
Chris Lattner08d2cc72009-01-31 07:26:06 +0000843 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000844 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000845 if (DemandedMask == 0) { // Not demanding any bits from V.
846 if (isa<UndefValue>(V))
847 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000848 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000849 }
850
Chris Lattner4598c942009-01-31 08:24:16 +0000851 if (Depth == 6) // Limit search depth.
852 return 0;
853
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000854 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
855 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
856
Dan Gohman1c8491e2009-04-25 17:12:48 +0000857 Instruction *I = dyn_cast<Instruction>(V);
858 if (!I) {
859 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
860 return 0; // Only analyze instructions.
861 }
862
Chris Lattner4598c942009-01-31 08:24:16 +0000863 // If there are multiple uses of this value and we aren't at the root, then
864 // we can't do any simplifications of the operands, because DemandedMask
865 // only reflects the bits demanded by *one* of the users.
866 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000867 // Despite the fact that we can't simplify this instruction in all User's
868 // context, we can at least compute the knownzero/knownone bits, and we can
869 // do simplifications that apply to *just* the one user if we know that
870 // this instruction has a simpler value in that context.
871 if (I->getOpcode() == Instruction::And) {
872 // If either the LHS or the RHS are Zero, the result is zero.
873 ComputeMaskedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1);
875 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
876 LHSKnownZero, LHSKnownOne, Depth+1);
877
878 // If all of the demanded bits are known 1 on one side, return the other.
879 // These bits cannot contribute to the result of the 'and' in this
880 // context.
881 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
882 (DemandedMask & ~LHSKnownZero))
883 return I->getOperand(0);
884 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
885 (DemandedMask & ~RHSKnownZero))
886 return I->getOperand(1);
887
888 // If all of the demanded bits in the inputs are known zeros, return zero.
889 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000890 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000891
892 } else if (I->getOpcode() == Instruction::Or) {
893 // We can simplify (X|Y) -> X or Y in the user's context if we know that
894 // only bits from X or Y are demanded.
895
896 // If either the LHS or the RHS are One, the result is One.
897 ComputeMaskedBits(I->getOperand(1), DemandedMask,
898 RHSKnownZero, RHSKnownOne, Depth+1);
899 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
900 LHSKnownZero, LHSKnownOne, Depth+1);
901
902 // If all of the demanded bits are known zero on one side, return the
903 // other. These bits cannot contribute to the result of the 'or' in this
904 // context.
905 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
906 (DemandedMask & ~LHSKnownOne))
907 return I->getOperand(0);
908 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
909 (DemandedMask & ~RHSKnownOne))
910 return I->getOperand(1);
911
912 // If all of the potentially set bits on one side are known to be set on
913 // the other side, just use the 'other' side.
914 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
915 (DemandedMask & (~RHSKnownZero)))
916 return I->getOperand(0);
917 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
918 (DemandedMask & (~LHSKnownZero)))
919 return I->getOperand(1);
920 }
921
Chris Lattner4598c942009-01-31 08:24:16 +0000922 // Compute the KnownZero/KnownOne bits to simplify things downstream.
923 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
924 return 0;
925 }
926
927 // If this is the root being simplified, allow it to have multiple uses,
928 // just set the DemandedMask to all bits so that we can try to simplify the
929 // operands. This allows visitTruncInst (for example) to simplify the
930 // operand of a trunc without duplicating all the logic below.
931 if (Depth == 0 && !V->hasOneUse())
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933
Reid Spencer8cb68342007-03-12 17:25:59 +0000934 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000935 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000936 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000937 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 case Instruction::And:
939 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If all of the demanded bits are known 1 on one side, return the other.
949 // These bits cannot contribute to the result of the 'and'.
950 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
951 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
954 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the demanded bits in the inputs are known zeros, return zero.
958 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000959 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000960
961 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000962 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // Output known-1 bits are only known if set in both the LHS & RHS.
966 RHSKnownOne &= LHSKnownOne;
967 // Output known-0 are known to be clear if zero in either the LHS | RHS.
968 RHSKnownZero |= LHSKnownZero;
969 break;
970 case Instruction::Or:
971 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
973 RHSKnownZero, RHSKnownOne, Depth+1) ||
974 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000975 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I;
977 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
978 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'or'.
982 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
983 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000985 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
986 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // If all of the potentially set bits on one side are known to be set on
990 // the other side, just use the 'other' side.
991 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
992 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
995 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000997
998 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000999 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
1002 // Output known-0 bits are only known if clear in both the LHS & RHS.
1003 RHSKnownZero &= LHSKnownZero;
1004 // Output known-1 are known to be set if set in either the LHS | RHS.
1005 RHSKnownOne |= LHSKnownOne;
1006 break;
1007 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001008 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1) ||
1010 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001011 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I;
1013 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1014 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001015
1016 // If all of the demanded bits are known zero on one side, return the other.
1017 // These bits cannot contribute to the result of the 'xor'.
1018 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001019 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001020 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022
1023 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1024 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1025 (RHSKnownOne & LHSKnownOne);
1026 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1027 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1028 (RHSKnownOne & LHSKnownZero);
1029
1030 // If all of the demanded bits are known to be zero on one side or the
1031 // other, turn this into an *inclusive* or.
1032 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1033 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1034 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001035 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001036 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001037 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 }
1039
1040 // If all of the demanded bits on one side are known, and all of the set
1041 // bits on that side are also known to be set on the other side, turn this
1042 // into an AND, as we know the bits will be cleared.
1043 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1044 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1045 // all known
1046 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001047 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001049 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 }
1052 }
1053
1054 // If the RHS is a constant, see if we can simplify it.
1055 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001056 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001057 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001058
1059 RHSKnownZero = KnownZeroOut;
1060 RHSKnownOne = KnownOneOut;
1061 break;
1062 }
1063 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1065 RHSKnownZero, RHSKnownOne, Depth+1) ||
1066 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1070 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001071
1072 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001073 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1074 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
1077 // Only known if known in both the LHS and RHS.
1078 RHSKnownOne &= LHSKnownOne;
1079 RHSKnownZero &= LHSKnownZero;
1080 break;
1081 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001082 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001083 DemandedMask.zext(truncBf);
1084 RHSKnownZero.zext(truncBf);
1085 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001087 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 DemandedMask.trunc(BitWidth);
1090 RHSKnownZero.trunc(BitWidth);
1091 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 break;
1094 }
1095 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001096 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001098
1099 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1100 if (const VectorType *SrcVTy =
1101 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1102 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1103 // Don't touch a bitcast between vectors of different element counts.
1104 return false;
1105 } else
1106 // Don't touch a scalar-to-vector bitcast.
1107 return false;
1108 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1109 // Don't touch a vector-to-scalar bitcast.
1110 return false;
1111
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001114 return I;
1115 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 break;
1117 case Instruction::ZExt: {
1118 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001119 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001120
Zhou Shengd48653a2007-03-29 04:45:55 +00001121 DemandedMask.trunc(SrcBitWidth);
1122 RHSKnownZero.trunc(SrcBitWidth);
1123 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 DemandedMask.zext(BitWidth);
1128 RHSKnownZero.zext(BitWidth);
1129 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001133 break;
1134 }
1135 case Instruction::SExt: {
1136 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001137 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001140 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001141
Zhou Sheng01542f32007-03-29 02:26:30 +00001142 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 // If any of the sign extended bits are demanded, we know that the sign
1144 // bit is demanded.
1145 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001146 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001147
Zhou Shengd48653a2007-03-29 04:45:55 +00001148 InputDemandedBits.trunc(SrcBitWidth);
1149 RHSKnownZero.trunc(SrcBitWidth);
1150 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001152 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001154 InputDemandedBits.zext(BitWidth);
1155 RHSKnownZero.zext(BitWidth);
1156 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001158
1159 // If the sign bit of the input is known set or clear, then we know the
1160 // top bits of the result.
1161
1162 // If the input sign bit is known zero, or if the NewBits are not demanded
1163 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001166 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1167 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001168 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 }
1171 break;
1172 }
1173 case Instruction::Add: {
1174 // Figure out what the input bits are. If the top bits of the and result
1175 // are not demanded, then the add doesn't demand them from its input
1176 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001177 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // If there is a constant on the RHS, there are a variety of xformations
1180 // we can do.
1181 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1182 // If null, this should be simplified elsewhere. Some of the xforms here
1183 // won't work if the RHS is zero.
1184 if (RHS->isZero())
1185 break;
1186
1187 // If the top bit of the output is demanded, demand everything from the
1188 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001189 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001190
1191 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001194 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001195
1196 // If the RHS of the add has bits set that can't affect the input, reduce
1197 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001198 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
1201 // Avoid excess work.
1202 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1203 break;
1204
1205 // Turn it into OR if input bits are zero.
1206 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1207 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001208 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001211 }
1212
1213 // We can say something about the output known-zero and known-one bits,
1214 // depending on potential carries from the input constant and the
1215 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1216 // bits set and the RHS constant is 0x01001, then we know we have a known
1217 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1218
1219 // To compute this, we first compute the potential carry bits. These are
1220 // the bits which may be modified. I'm not aware of a better way to do
1221 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001223 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001224
1225 // Now that we know which bits have carries, compute the known-1/0 sets.
1226
1227 // Bits are known one if they are known zero in one operand and one in the
1228 // other, and there is no input carry.
1229 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1230 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1231
1232 // Bits are known zero if they are known zero in both operands and there
1233 // is no input carry.
1234 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1235 } else {
1236 // If the high-bits of this ADD are not demanded, then it does not demand
1237 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001238 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 // Right fill the mask of bits for this ADD to demand the most
1240 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001241 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1243 LHSKnownZero, LHSKnownOne, Depth+1) ||
1244 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001246 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 }
1248 }
1249 break;
1250 }
1251 case Instruction::Sub:
1252 // If the high-bits of this SUB are not demanded, then it does not demand
1253 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001254 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 // Right fill the mask of bits for this SUB to demand the most
1256 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001257 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001258 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1260 LHSKnownZero, LHSKnownOne, Depth+1) ||
1261 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001263 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001265 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1266 // the known zeros and ones.
1267 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 break;
1269 case Instruction::Shl:
1270 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001271 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 return I;
1276 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 RHSKnownZero <<= ShiftAmt;
1278 RHSKnownOne <<= ShiftAmt;
1279 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001280 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001281 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 }
1283 break;
1284 case Instruction::LShr:
1285 // For a logical shift right
1286 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001287 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001288
Reid Spencer8cb68342007-03-12 17:25:59 +00001289 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001290 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 return I;
1294 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1296 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001297 if (ShiftAmt) {
1298 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001299 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001300 RHSKnownZero |= HighBits; // high bits known zero.
1301 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 }
1303 break;
1304 case Instruction::AShr:
1305 // If this is an arithmetic shift right and only the low-bit is set, we can
1306 // always convert this into a logical shr, even if the shift amount is
1307 // variable. The low bit of the shift cannot be an input sign bit unless
1308 // the shift amount is >= the size of the datatype, which is undefined.
1309 if (DemandedMask == 1) {
1310 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001313 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001315
1316 // If the sign bit is the only bit demanded by this ashr, then there is no
1317 // need to do it, the shift doesn't change the high bit.
1318 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001320
1321 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001322 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001323
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001325 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001326 // If any of the "high bits" are demanded, we should set the sign bit as
1327 // demanded.
1328 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1329 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return I;
1333 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001335 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1337 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1338
1339 // Handle the sign bits.
1340 APInt SignBit(APInt::getSignBit(BitWidth));
1341 // Adjust to where it is now in the mask.
1342 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1343
1344 // If the input sign bit is known to be zero, or if none of the top bits
1345 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001346 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 (HighBits & ~DemandedMask) == HighBits) {
1348 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1353 RHSKnownOne |= HighBits;
1354 }
1355 }
1356 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 case Instruction::SRem:
1358 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001359 APInt RA = Rem->getValue().abs();
1360 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001361 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001363
Nick Lewycky8e394322008-11-02 02:41:50 +00001364 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001366 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001367 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369
1370 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1371 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372
1373 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001374
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001376 }
1377 }
1378 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001379 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001380 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1381 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1383 KnownZero2, KnownOne2, Depth+1) ||
1384 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001385 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001386 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001387
Chris Lattner455e9ab2009-01-21 18:09:24 +00001388 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001389 Leaders = std::max(Leaders,
1390 KnownZero2.countLeadingOnes());
1391 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001392 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001394 case Instruction::Call:
1395 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1396 switch (II->getIntrinsicID()) {
1397 default: break;
1398 case Intrinsic::bswap: {
1399 // If the only bits demanded come from one byte of the bswap result,
1400 // just shift the input byte into position to eliminate the bswap.
1401 unsigned NLZ = DemandedMask.countLeadingZeros();
1402 unsigned NTZ = DemandedMask.countTrailingZeros();
1403
1404 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1405 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1406 // have 14 leading zeros, round to 8.
1407 NLZ &= ~7;
1408 NTZ &= ~7;
1409 // If we need exactly one byte, we can do this transformation.
1410 if (BitWidth-NLZ-NTZ == 8) {
1411 unsigned ResultBit = NTZ;
1412 unsigned InputBit = BitWidth-NTZ-8;
1413
1414 // Replace this with either a left or right shift to get the byte into
1415 // the right place.
1416 Instruction *NewVal;
1417 if (InputBit > ResultBit)
1418 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001419 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001420 else
1421 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001422 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001423 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001424 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001425 }
1426
1427 // TODO: Could compute known zero/one bits based on the input.
1428 break;
1429 }
1430 }
1431 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001432 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001433 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001434 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001435
1436 // If the client is only demanding bits that we know, return the known
1437 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001438 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001439 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001440 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001441 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001442 return C;
1443 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001444 return false;
1445}
1446
Chris Lattner867b99f2006-10-05 06:55:50 +00001447
Mon P Wangaeb06d22008-11-10 04:46:22 +00001448/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001449/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001450/// actually used by the caller. This method analyzes which elements of the
1451/// operand are undef and returns that information in UndefElts.
1452///
1453/// If the information about demanded elements can be used to simplify the
1454/// operation, the operation is simplified, then the resultant value is
1455/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001456Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1457 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001460 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001461 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001462
1463 if (isa<UndefValue>(V)) {
1464 // If the entire vector is undefined, just return this info.
1465 UndefElts = EltMask;
1466 return 0;
1467 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1468 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001469 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001471
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001473 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1474 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001475 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001476
1477 std::vector<Constant*> Elts;
1478 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001479 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001481 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1483 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001484 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 } else { // Otherwise, defined.
1486 Elts.push_back(CP->getOperand(i));
1487 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001488
Chris Lattner867b99f2006-10-05 06:55:50 +00001489 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001490 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 return NewCP != CP ? NewCP : 0;
1492 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001493 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001495
1496 // Check if this is identity. If so, return 0 since we are not simplifying
1497 // anything.
1498 if (DemandedElts == ((1ULL << VWidth) -1))
1499 return 0;
1500
Reid Spencer9d6565a2007-02-15 02:26:10 +00001501 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001502 Constant *Zero = Context->getNullValue(EltTy);
1503 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001505 for (unsigned i = 0; i != VWidth; ++i) {
1506 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1507 Elts.push_back(Elt);
1508 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001509 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001510 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 }
1512
Dan Gohman488fbfc2008-09-09 18:11:14 +00001513 // Limit search depth.
1514 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001515 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001516
1517 // If multiple users are using the root value, procede with
1518 // simplification conservatively assuming that all elements
1519 // are needed.
1520 if (!V->hasOneUse()) {
1521 // Quit if we find multiple users of a non-root value though.
1522 // They'll be handled when it's their turn to be visited by
1523 // the main instcombine process.
1524 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001526 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001527
1528 // Conservatively assume that all elements are needed.
1529 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 }
1531
1532 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001533 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001536 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 Value *TmpV;
1538 switch (I->getOpcode()) {
1539 default: break;
1540
1541 case Instruction::InsertElement: {
1542 // If this is a variable index, we don't know which element it overwrites.
1543 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001544 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001545 if (Idx == 0) {
1546 // Note that we can't propagate undef elt info, because we don't know
1547 // which elt is getting updated.
1548 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1549 UndefElts2, Depth+1);
1550 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551 break;
1552 }
1553
1554 // If this is inserting an element that isn't demanded, remove this
1555 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001556 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001557 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 return AddSoonDeadInstToWorklist(*I, 0);
1559
1560 // Otherwise, the element inserted overwrites whatever was there, so the
1561 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001562 APInt DemandedElts2 = DemandedElts;
1563 DemandedElts2.clear(IdxNo);
1564 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 UndefElts, Depth+1);
1566 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1567
1568 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001569 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 break;
1571 }
1572 case Instruction::ShuffleVector: {
1573 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001574 uint64_t LHSVWidth =
1575 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001576 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001578 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001579 unsigned MaskVal = Shuffle->getMaskValue(i);
1580 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001581 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001583 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001584 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 else
Evan Cheng388df622009-02-03 10:05:09 +00001586 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 }
1588 }
1589 }
1590
Nate Begeman7b254672009-02-11 22:36:25 +00001591 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001593 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001594 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595
Nate Begeman7b254672009-02-11 22:36:25 +00001596 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1598 UndefElts3, Depth+1);
1599 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1600
1601 bool NewUndefElts = false;
1602 for (unsigned i = 0; i < VWidth; i++) {
1603 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001604 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001605 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001606 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001607 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001608 NewUndefElts = true;
1609 UndefElts.set(i);
1610 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001612 if (UndefElts3[MaskVal - LHSVWidth]) {
1613 NewUndefElts = true;
1614 UndefElts.set(i);
1615 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 }
1617 }
1618
1619 if (NewUndefElts) {
1620 // Add additional discovered undefs.
1621 std::vector<Constant*> Elts;
1622 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001623 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001624 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001625 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001626 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001627 Shuffle->getMaskValue(i)));
1628 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001629 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001630 MadeChange = true;
1631 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001632 break;
1633 }
Chris Lattner69878332007-04-14 22:29:23 +00001634 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001635 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001636 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1637 if (!VTy) break;
1638 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001639 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001640 unsigned Ratio;
1641
1642 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001643 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001644 // elements as are demanded of us.
1645 Ratio = 1;
1646 InputDemandedElts = DemandedElts;
1647 } else if (VWidth > InVWidth) {
1648 // Untested so far.
1649 break;
1650
1651 // If there are more elements in the result than there are in the source,
1652 // then an input element is live if any of the corresponding output
1653 // elements are live.
1654 Ratio = VWidth/InVWidth;
1655 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001656 if (DemandedElts[OutIdx])
1657 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001658 }
1659 } else {
1660 // Untested so far.
1661 break;
1662
1663 // If there are more elements in the source than there are in the result,
1664 // then an input element is live if the corresponding output element is
1665 // live.
1666 Ratio = InVWidth/VWidth;
1667 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001668 if (DemandedElts[InIdx/Ratio])
1669 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001670 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001671
Chris Lattner69878332007-04-14 22:29:23 +00001672 // div/rem demand all inputs, because they don't want divide by zero.
1673 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1674 UndefElts2, Depth+1);
1675 if (TmpV) {
1676 I->setOperand(0, TmpV);
1677 MadeChange = true;
1678 }
1679
1680 UndefElts = UndefElts2;
1681 if (VWidth > InVWidth) {
1682 assert(0 && "Unimp");
1683 // If there are more elements in the result than there are in the source,
1684 // then an output element is undef if the corresponding input element is
1685 // undef.
1686 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001687 if (UndefElts2[OutIdx/Ratio])
1688 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001689 } else if (VWidth < InVWidth) {
1690 assert(0 && "Unimp");
1691 // If there are more elements in the source than there are in the result,
1692 // then a result element is undef if all of the corresponding input
1693 // elements are undef.
1694 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1695 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001696 if (!UndefElts2[InIdx]) // Not undef?
1697 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001698 }
1699 break;
1700 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001701 case Instruction::And:
1702 case Instruction::Or:
1703 case Instruction::Xor:
1704 case Instruction::Add:
1705 case Instruction::Sub:
1706 case Instruction::Mul:
1707 // div/rem demand all inputs, because they don't want divide by zero.
1708 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1709 UndefElts, Depth+1);
1710 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1712 UndefElts2, Depth+1);
1713 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1714
1715 // Output elements are undefined if both are undefined. Consider things
1716 // like undef&0. The result is known zero, not undef.
1717 UndefElts &= UndefElts2;
1718 break;
1719
1720 case Instruction::Call: {
1721 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1722 if (!II) break;
1723 switch (II->getIntrinsicID()) {
1724 default: break;
1725
1726 // Binary vector operations that work column-wise. A dest element is a
1727 // function of the corresponding input elements from the two inputs.
1728 case Intrinsic::x86_sse_sub_ss:
1729 case Intrinsic::x86_sse_mul_ss:
1730 case Intrinsic::x86_sse_min_ss:
1731 case Intrinsic::x86_sse_max_ss:
1732 case Intrinsic::x86_sse2_sub_sd:
1733 case Intrinsic::x86_sse2_mul_sd:
1734 case Intrinsic::x86_sse2_min_sd:
1735 case Intrinsic::x86_sse2_max_sd:
1736 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1737 UndefElts, Depth+1);
1738 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1740 UndefElts2, Depth+1);
1741 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1742
1743 // If only the low elt is demanded and this is a scalarizable intrinsic,
1744 // scalarize it now.
1745 if (DemandedElts == 1) {
1746 switch (II->getIntrinsicID()) {
1747 default: break;
1748 case Intrinsic::x86_sse_sub_ss:
1749 case Intrinsic::x86_sse_mul_ss:
1750 case Intrinsic::x86_sse2_sub_sd:
1751 case Intrinsic::x86_sse2_mul_sd:
1752 // TODO: Lower MIN/MAX/ABS/etc
1753 Value *LHS = II->getOperand(1);
1754 Value *RHS = II->getOperand(2);
1755 // Extract the element as scalars.
1756 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1757 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1758
1759 switch (II->getIntrinsicID()) {
1760 default: assert(0 && "Case stmts out of sync!");
1761 case Intrinsic::x86_sse_sub_ss:
1762 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001763 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 II->getName()), *II);
1765 break;
1766 case Intrinsic::x86_sse_mul_ss:
1767 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001768 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001769 II->getName()), *II);
1770 break;
1771 }
1772
1773 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001774 InsertElementInst::Create(
1775 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001776 InsertNewInstBefore(New, *II);
1777 AddSoonDeadInstToWorklist(*II, 0);
1778 return New;
1779 }
1780 }
1781
1782 // Output elements are undefined if both are undefined. Consider things
1783 // like undef&0. The result is known zero, not undef.
1784 UndefElts &= UndefElts2;
1785 break;
1786 }
1787 break;
1788 }
1789 }
1790 return MadeChange ? I : 0;
1791}
1792
Dan Gohman45b4e482008-05-19 22:14:15 +00001793
Chris Lattner564a7272003-08-13 19:01:45 +00001794/// AssociativeOpt - Perform an optimization on an associative operator. This
1795/// function is designed to check a chain of associative operators for a
1796/// potential to apply a certain optimization. Since the optimization may be
1797/// applicable if the expression was reassociated, this checks the chain, then
1798/// reassociates the expression as necessary to expose the optimization
1799/// opportunity. This makes use of a special Functor, which must define
1800/// 'shouldApply' and 'apply' methods.
1801///
1802template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001803static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001804 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001805 unsigned Opcode = Root.getOpcode();
1806 Value *LHS = Root.getOperand(0);
1807
1808 // Quick check, see if the immediate LHS matches...
1809 if (F.shouldApply(LHS))
1810 return F.apply(Root);
1811
1812 // Otherwise, if the LHS is not of the same opcode as the root, return.
1813 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001814 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001815 // Should we apply this transform to the RHS?
1816 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1817
1818 // If not to the RHS, check to see if we should apply to the LHS...
1819 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1820 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1821 ShouldApply = true;
1822 }
1823
1824 // If the functor wants to apply the optimization to the RHS of LHSI,
1825 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1826 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001827 // Now all of the instructions are in the current basic block, go ahead
1828 // and perform the reassociation.
1829 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1830
1831 // First move the selected RHS to the LHS of the root...
1832 Root.setOperand(0, LHSI->getOperand(1));
1833
1834 // Make what used to be the LHS of the root be the user of the root...
1835 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001836 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001837 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001838 return 0;
1839 }
Chris Lattner65725312004-04-16 18:08:07 +00001840 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001841 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001842 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001843 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001844 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001845
1846 // Now propagate the ExtraOperand down the chain of instructions until we
1847 // get to LHSI.
1848 while (TmpLHSI != LHSI) {
1849 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001850 // Move the instruction to immediately before the chain we are
1851 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001852 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001853 ARI = NextLHSI;
1854
Chris Lattner564a7272003-08-13 19:01:45 +00001855 Value *NextOp = NextLHSI->getOperand(1);
1856 NextLHSI->setOperand(1, ExtraOperand);
1857 TmpLHSI = NextLHSI;
1858 ExtraOperand = NextOp;
1859 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001860
Chris Lattner564a7272003-08-13 19:01:45 +00001861 // Now that the instructions are reassociated, have the functor perform
1862 // the transformation...
1863 return F.apply(Root);
1864 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001865
Chris Lattner564a7272003-08-13 19:01:45 +00001866 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1867 }
1868 return 0;
1869}
1870
Dan Gohman844731a2008-05-13 00:00:25 +00001871namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001872
Nick Lewycky02d639f2008-05-23 04:34:58 +00001873// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001874struct AddRHS {
1875 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001876 LLVMContext *Context;
1877 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001878 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1879 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001880 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001881 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001882 }
1883};
1884
1885// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1886// iff C1&C2 == 0
1887struct AddMaskingAnd {
1888 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001889 LLVMContext *Context;
1890 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001891 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001892 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001893 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001894 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001895 }
1896 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001897 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001898 }
1899};
1900
Dan Gohman844731a2008-05-13 00:00:25 +00001901}
1902
Chris Lattner6e7ba452005-01-01 16:22:27 +00001903static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001904 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001905 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001906
Reid Spencer3da59db2006-11-27 01:05:10 +00001907 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001908 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001909 }
1910
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1913 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001914
Chris Lattner2eefe512004-04-09 19:05:30 +00001915 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1916 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001917 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1918 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001919 }
1920
1921 Value *Op0 = SO, *Op1 = ConstOperand;
1922 if (!ConstIsRHS)
1923 std::swap(Op0, Op1);
1924 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001926 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001927 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001928 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1929 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001930 else {
Torok Edwin7d696d82009-07-11 13:10:19 +00001931 LLVM_UNREACHABLE("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001932 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001933 return IC->InsertNewInstBefore(New, I);
1934}
1935
1936// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1937// constant as the other operand, try to fold the binary operator into the
1938// select arguments. This also works for Cast instructions, which obviously do
1939// not have a second operand.
1940static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1941 InstCombiner *IC) {
1942 // Don't modify shared select instructions
1943 if (!SI->hasOneUse()) return 0;
1944 Value *TV = SI->getOperand(1);
1945 Value *FV = SI->getOperand(2);
1946
1947 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001948 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001949 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001950
Chris Lattner6e7ba452005-01-01 16:22:27 +00001951 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1952 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1953
Gabor Greif051a9502008-04-06 20:25:17 +00001954 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1955 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001956 }
1957 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001958}
1959
Chris Lattner4e998b22004-09-29 05:07:12 +00001960
1961/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1962/// node as operand #0, see if we can fold the instruction into the PHI (which
1963/// is only possible if all operands to the PHI are constants).
1964Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1965 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001966 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001967 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001968
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 // Check to see if all of the operands of the PHI are constants. If there is
1970 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001971 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001972 BasicBlock *NonConstBB = 0;
1973 for (unsigned i = 0; i != NumPHIValues; ++i)
1974 if (!isa<Constant>(PN->getIncomingValue(i))) {
1975 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001976 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 NonConstBB = PN->getIncomingBlock(i);
1978
1979 // If the incoming non-constant value is in I's block, we have an infinite
1980 // loop.
1981 if (NonConstBB == I.getParent())
1982 return 0;
1983 }
1984
1985 // If there is exactly one non-constant value, we can insert a copy of the
1986 // operation in that block. However, if this is a critical edge, we would be
1987 // inserting the computation one some other paths (e.g. inside a loop). Only
1988 // do this if the pred block is unconditionally branching into the phi block.
1989 if (NonConstBB) {
1990 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991 if (!BI || !BI->isUnconditional()) return 0;
1992 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001993
1994 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001995 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001996 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001997 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001998 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001999
2000 // Next, add all of the operands to the PHI.
2001 if (I.getNumOperands() == 2) {
2002 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002003 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002004 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002006 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00002007 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008 else
Owen Andersond672ecb2009-07-03 00:17:18 +00002009 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010 } else {
2011 assert(PN->getIncomingBlock(i) == NonConstBB);
2012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002013 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 PN->getIncomingValue(i), C, "phitmp",
2015 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002016 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002017 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002018 CI->getPredicate(),
2019 PN->getIncomingValue(i), C, "phitmp",
2020 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 else
2022 assert(0 && "Unknown binop!");
2023
Chris Lattnerdbab3862007-03-02 21:28:56 +00002024 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 }
2026 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002027 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002028 } else {
2029 CastInst *CI = cast<CastInst>(&I);
2030 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002031 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002032 Value *InV;
2033 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002034 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 } else {
2036 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002037 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002038 I.getType(), "phitmp",
2039 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002040 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002041 }
2042 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002043 }
2044 }
2045 return ReplaceInstUsesWith(I, NewPN);
2046}
2047
Chris Lattner2454a2e2008-01-29 06:52:45 +00002048
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002049/// WillNotOverflowSignedAdd - Return true if we can prove that:
2050/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2051/// This basically requires proving that the add in the original type would not
2052/// overflow to change the sign bit or have a carry out.
2053bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2054 // There are different heuristics we can use for this. Here are some simple
2055 // ones.
2056
2057 // Add has the property that adding any two 2's complement numbers can only
2058 // have one carry bit which can change a sign. As such, if LHS and RHS each
2059 // have at least two sign bits, we know that the addition of the two values will
2060 // sign extend fine.
2061 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2062 return true;
2063
2064
2065 // If one of the operands only has one non-zero bit, and if the other operand
2066 // has a known-zero bit in a more significant place than it (not including the
2067 // sign bit) the ripple may go up to and fill the zero, but won't change the
2068 // sign. For example, (X & ~4) + 1.
2069
2070 // TODO: Implement.
2071
2072 return false;
2073}
2074
Chris Lattner2454a2e2008-01-29 06:52:45 +00002075
Chris Lattner7e708292002-06-25 16:13:24 +00002076Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002077 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002078 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002079
Chris Lattner66331a42004-04-10 22:01:55 +00002080 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002081 // X + undef -> undef
2082 if (isa<UndefValue>(RHS))
2083 return ReplaceInstUsesWith(I, RHS);
2084
Chris Lattner66331a42004-04-10 22:01:55 +00002085 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002086 if (RHSC->isNullValue())
2087 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002088
Chris Lattner66331a42004-04-10 22:01:55 +00002089 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002090 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002091 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002092 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002093 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002094 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002095
2096 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2097 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002098 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002099 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002100
2101 // zext(i1) - 1 -> select i1, 0, -1
2102 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2103 if (CI->isAllOnesValue() &&
2104 ZI->getOperand(0)->getType() == Type::Int1Ty)
2105 return SelectInst::Create(ZI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002106 Context->getNullValue(I.getType()),
2107 Context->getConstantIntAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002108 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002109
2110 if (isa<PHINode>(LHS))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2112 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002113
Chris Lattner4f637d42006-01-06 17:59:59 +00002114 ConstantInt *XorRHS = 0;
2115 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002116 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002118 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002119 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002120
Zhou Sheng4351c642007-04-02 08:20:41 +00002121 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002122 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002124 do {
2125 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002126 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002128 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002130 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002131 if (!MaskedValueIsZero(XorLHS,
2132 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002133 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002134 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002135 }
2136 }
2137 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002138 C0080Val = APIntOps::lshr(C0080Val, Size);
2139 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002141
Reid Spencer35c38852007-03-28 01:36:16 +00002142 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002143 // with funny bit widths then this switch statement should be removed. It
2144 // is just here to get the size of the "middle" type back up to something
2145 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002146 const Type *MiddleType = 0;
2147 switch (Size) {
2148 default: break;
2149 case 32: MiddleType = Type::Int32Ty; break;
2150 case 16: MiddleType = Type::Int16Ty; break;
2151 case 8: MiddleType = Type::Int8Ty; break;
2152 }
2153 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002154 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002155 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002156 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002157 }
2158 }
Chris Lattner66331a42004-04-10 22:01:55 +00002159 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002160
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002161 if (I.getType() == Type::Int1Ty)
2162 return BinaryOperator::CreateXor(LHS, RHS);
2163
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002164 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002165 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002166 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002168
2169 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170 if (RHSI->getOpcode() == Instruction::Sub)
2171 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2172 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173 }
2174 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175 if (LHSI->getOpcode() == Instruction::Sub)
2176 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2177 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178 }
Robert Bocchino71698282004-07-27 21:02:21 +00002179 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002180
Chris Lattner5c4afb92002-05-08 22:46:53 +00002181 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002182 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002183 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002184 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002185 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002186 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002187 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002188 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002189 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002190 }
2191
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002192 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002193 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002194
2195 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002196 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002197 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002199
Misha Brukmanfd939082005-04-21 23:48:37 +00002200
Chris Lattner50af16a2004-11-13 19:50:12 +00002201 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002202 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002203 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002204 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002205
2206 // X*C1 + X*C2 --> X * (C1+C2)
2207 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002208 if (X == dyn_castFoldableMul(RHS, C1, Context))
2209 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002210 }
2211
2212 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002213 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002215
Chris Lattnere617c9e2007-01-05 02:17:46 +00002216 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002217 if (dyn_castNotVal(LHS, Context) == RHS ||
2218 dyn_castNotVal(RHS, Context) == LHS)
2219 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002220
Chris Lattnerad3448c2003-02-18 19:57:07 +00002221
Chris Lattner564a7272003-08-13 19:01:45 +00002222 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002224 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002225 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002226
2227 // A+B --> A|B iff A and B have no bits set in common.
2228 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230 APInt LHSKnownOne(IT->getBitWidth(), 0);
2231 APInt LHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233 if (LHSKnownZero != 0) {
2234 APInt RHSKnownOne(IT->getBitWidth(), 0);
2235 APInt RHSKnownZero(IT->getBitWidth(), 0);
2236 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237
2238 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002239 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002240 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002241 }
2242 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002243
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002244 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002245 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002246 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002247 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002249 if (W != Y) {
2250 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002251 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002252 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002253 std::swap(W, X);
2254 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 std::swap(Y, Z);
2256 std::swap(W, X);
2257 }
2258 }
2259
2260 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002262 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002264 }
2265 }
2266 }
2267
Chris Lattner6b032052003-10-02 15:11:26 +00002268 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002269 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002270 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002271 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002272
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002274 if (LHS->hasOneUse() &&
2275 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002276 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277 if (Anded == CRHS) {
2278 // See if all bits from the first bit set in the Add RHS up are included
2279 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002280 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002281
2282 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002283 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284
2285 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002286 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002287
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002288 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002290 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002291 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002292 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002293 }
2294 }
2295 }
2296
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002297 // Try to fold constant add into select arguments.
2298 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002299 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002300 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002301 }
2302
Reid Spencer1628cec2006-10-26 06:15:43 +00002303 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002304 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002305 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002306 CastInst *CI = dyn_cast<CastInst>(LHS);
2307 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308 if (!CI) {
2309 CI = dyn_cast<CastInst>(RHS);
2310 Other = LHS;
2311 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002312 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002313 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002314 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002315 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002316 unsigned AS =
2317 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002318 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002319 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002320 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002321 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002322 }
2323 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002324
Chris Lattner42790482007-12-20 01:56:58 +00002325 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002326 {
2327 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002328 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002329 if (!SI) {
2330 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002331 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002332 }
Chris Lattner42790482007-12-20 01:56:58 +00002333 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002334 Value *TV = SI->getTrueValue();
2335 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002336 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002337
2338 // Can we fold the add into the argument of the select?
2339 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002340 if (match(FV, m_Zero(), *Context) &&
2341 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002342 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002343 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002344 if (match(TV, m_Zero(), *Context) &&
2345 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002346 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002347 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002348 }
2349 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002350
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002351 // Check for (add (sext x), y), see if we can merge this into an
2352 // integer add followed by a sext.
2353 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354 // (add (sext x), cst) --> (sext (add x, cst'))
2355 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002357 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002358 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002359 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002360 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361 // Insert the new, smaller add.
2362 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2363 CI, "addconv");
2364 InsertNewInstBefore(NewAdd, I);
2365 return new SExtInst(NewAdd, I.getType());
2366 }
2367 }
2368
2369 // (add (sext x), (sext y)) --> (sext (add int x, y))
2370 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371 // Only do this if x/y have the same type, if at last one of them has a
2372 // single use (so we don't increase the number of sexts), and if the
2373 // integer add will not overflow.
2374 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377 RHSConv->getOperand(0))) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0),
2381 "addconv");
2382 InsertNewInstBefore(NewAdd, I);
2383 return new SExtInst(NewAdd, I.getType());
2384 }
2385 }
2386 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002387
2388 return Changed ? &I : 0;
2389}
2390
2391Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392 bool Changed = SimplifyCommutative(I);
2393 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396 // X + 0 --> X
2397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002398 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002399 (I.getType())->getValueAPF()))
2400 return ReplaceInstUsesWith(I, LHS);
2401 }
2402
2403 if (isa<PHINode>(LHS))
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2405 return NV;
2406 }
2407
2408 // -A + B --> B - A
2409 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002410 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002411 return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413 // A + -B --> A - B
2414 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002415 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002416 return BinaryOperator::CreateFSub(LHS, V);
2417
2418 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2419 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421 return ReplaceInstUsesWith(I, LHS);
2422
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002423 // Check for (add double (sitofp x), y), see if we can merge this into an
2424 // integer add followed by a promotion.
2425 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427 // ... if the constant fits in the integer value. This is useful for things
2428 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429 // requires a constant pool load, and generally allows the add to be better
2430 // instcombined.
2431 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002433 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002434 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002435 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002436 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437 // Insert the new integer add.
2438 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2439 CI, "addconv");
2440 InsertNewInstBefore(NewAdd, I);
2441 return new SIToFPInst(NewAdd, I.getType());
2442 }
2443 }
2444
2445 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447 // Only do this if x/y have the same type, if at last one of them has a
2448 // single use (so we don't increase the number of int->fp conversions),
2449 // and if the integer add will not overflow.
2450 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453 RHSConv->getOperand(0))) {
2454 // Insert the new integer add.
2455 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0),
2457 "addconv");
2458 InsertNewInstBefore(NewAdd, I);
2459 return new SIToFPInst(NewAdd, I.getType());
2460 }
2461 }
2462 }
2463
Chris Lattner7e708292002-06-25 16:13:24 +00002464 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002465}
2466
Chris Lattner7e708292002-06-25 16:13:24 +00002467Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002469
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002470 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002471 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002472
Chris Lattner233f7dc2002-08-12 21:17:25 +00002473 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002474 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002476
Chris Lattnere87597f2004-10-16 18:11:37 +00002477 if (isa<UndefValue>(Op0))
2478 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2479 if (isa<UndefValue>(Op1))
2480 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2481
Chris Lattnerd65460f2003-11-05 01:06:05 +00002482 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002484 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002486
Chris Lattnerd65460f2003-11-05 01:06:05 +00002487 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002488 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002489 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002490 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002491
Chris Lattner76b7a062007-01-15 07:02:54 +00002492 // -(X >>u 31) -> (X >>s 31)
2493 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002494 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002495 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002496 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002497 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002498 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002499 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002500 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002501 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002502 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002503 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002504 }
2505 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002506 }
2507 else if (SI->getOpcode() == Instruction::AShr) {
2508 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002510 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002511 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002512 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002513 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002514 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002515 }
2516 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002517 }
2518 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002519 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002520
2521 // Try to fold constant sub into select arguments.
2522 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002524 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002525 }
2526
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002527 if (I.getType() == Type::Int1Ty)
2528 return BinaryOperator::CreateXor(Op0, Op1);
2529
Chris Lattner43d84d62005-04-07 16:15:25 +00002530 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002531 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002532 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002533 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002534 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002535 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002536 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002539 return BinaryOperator::CreateSub(
2540 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002541 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002542 }
2543
Chris Lattnerfd059242003-10-15 16:48:29 +00002544 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002545 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546 // is not used by anyone else...
2547 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002548 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002549 // Swap the two operands of the subexpr...
2550 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551 Op1I->setOperand(0, IIOp1);
2552 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002553
Chris Lattnera2881962003-02-18 19:28:33 +00002554 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002555 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002556 }
2557
2558 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559 //
2560 if (Op1I->getOpcode() == Instruction::And &&
2561 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
Chris Lattnerf523d062004-06-09 05:08:07 +00002564 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002565 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2566 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002567 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002568
Reid Spencerac5209e2006-10-16 23:08:08 +00002569 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002570 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002571 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002572 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002573 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002575 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002576
Chris Lattnerad3448c2003-02-18 19:57:07 +00002577 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002578 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002579 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2580 Constant *CP1 =
2581 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002582 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002583 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002584 }
Chris Lattner40371712002-05-09 01:29:19 +00002585 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002586 }
Chris Lattnera2881962003-02-18 19:28:33 +00002587
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002588 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2589 if (Op0I->getOpcode() == Instruction::Add) {
2590 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2591 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2592 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2593 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2594 } else if (Op0I->getOpcode() == Instruction::Sub) {
2595 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2596 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002597 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002598 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002599
Chris Lattner50af16a2004-11-13 19:50:12 +00002600 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002601 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002602 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002603 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002604
Chris Lattner50af16a2004-11-13 19:50:12 +00002605 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002606 if (X == dyn_castFoldableMul(Op1, C2, Context))
2607 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002608 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002609 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002610}
2611
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002612Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2613 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2614
2615 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002616 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002617 return BinaryOperator::CreateFAdd(Op0, V);
2618
2619 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2620 if (Op1I->getOpcode() == Instruction::FAdd) {
2621 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2622 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2623 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2624 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2625 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002626 }
2627
2628 return 0;
2629}
2630
Chris Lattnera0141b92007-07-15 20:42:37 +00002631/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632/// comparison only checks the sign bit. If it only checks the sign bit, set
2633/// TrueIfSigned if the result of the comparison is true when the input value is
2634/// signed.
2635static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002637 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002638 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2639 TrueIfSigned = true;
2640 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002641 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2642 TrueIfSigned = true;
2643 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002644 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2645 TrueIfSigned = false;
2646 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002647 case ICmpInst::ICMP_UGT:
2648 // True if LHS u> RHS and RHS == high-bit-mask - 1
2649 TrueIfSigned = true;
2650 return RHS->getValue() ==
2651 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652 case ICmpInst::ICMP_UGE:
2653 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002655 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002656 default:
2657 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002658 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002659}
2660
Chris Lattner7e708292002-06-25 16:13:24 +00002661Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002662 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002663 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002664
Dan Gohman77b81fe2009-06-04 17:12:12 +00002665 // TODO: If Op1 is undef and Op0 is finite, return zero.
2666 if (!I.getType()->isFPOrFPVector() &&
2667 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002668 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002669
Chris Lattner233f7dc2002-08-12 21:17:25 +00002670 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002671 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002673
2674 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002675 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002676 if (SI->getOpcode() == Instruction::Shl)
2677 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002679 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002680
Zhou Sheng843f07672007-04-19 05:39:12 +00002681 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002682 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2683 if (CI->equalsInt(1)) // X * 1 == X
2684 return ReplaceInstUsesWith(I, Op0);
2685 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002687
Zhou Sheng97b52c22007-03-29 01:57:21 +00002688 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002689 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002690 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002691 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002692 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002693 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002694 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002695
2696 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2698 return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700 // As above, vector X*splat(1.0) -> X in all defined cases.
2701 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703 if (CI->equalsInt(1))
2704 return ReplaceInstUsesWith(I, Op0);
2705 }
2706 }
Chris Lattnera2881962003-02-18 19:28:33 +00002707 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002708
2709 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002711 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002712 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002713 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002714 Op1, "tmp");
2715 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002716 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002717 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002718 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002719
2720 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002721
2722 // Try to fold constant mul into select arguments.
2723 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002724 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002725 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002726
2727 if (isa<PHINode>(Op0))
2728 if (Instruction *NV = FoldOpIntoPhi(I))
2729 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002730 }
2731
Owen Andersond672ecb2009-07-03 00:17:18 +00002732 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2733 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002735
Nick Lewycky0c730792008-11-21 07:33:58 +00002736 // (X / Y) * Y = X - (X % Y)
2737 // (X / Y) * -Y = (X % Y) - X
2738 {
2739 Value *Op1 = I.getOperand(1);
2740 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741 if (!BO ||
2742 (BO->getOpcode() != Instruction::UDiv &&
2743 BO->getOpcode() != Instruction::SDiv)) {
2744 Op1 = Op0;
2745 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002747 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002748 if (BO && BO->hasOneUse() &&
2749 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750 (BO->getOpcode() == Instruction::UDiv ||
2751 BO->getOpcode() == Instruction::SDiv)) {
2752 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754 Instruction *Rem;
2755 if (BO->getOpcode() == Instruction::UDiv)
2756 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757 else
2758 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760 InsertNewInstBefore(Rem, I);
2761 Rem->takeName(BO);
2762
2763 if (Op1BO == Op1)
2764 return BinaryOperator::CreateSub(Op0BO, Rem);
2765 else
2766 return BinaryOperator::CreateSub(Rem, Op0BO);
2767 }
2768 }
2769
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002770 if (I.getType() == Type::Int1Ty)
2771 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773 // If one of the operands of the multiply is a cast from a boolean value, then
2774 // we know the bool is either zero or one, so this is a 'masking' multiply.
2775 // See if we can simplify things based on how the boolean was originally
2776 // formed.
2777 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002778 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002779 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002780 BoolCast = CI;
2781 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002782 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002783 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 BoolCast = CI;
2785 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002786 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002787 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002789 bool TIS = false;
2790
Reid Spencere4d87aa2006-12-23 06:05:41 +00002791 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002792 // multiply into a shift/and combination.
2793 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002794 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002796 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002797 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002798 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002799 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002800 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002802 BoolCast->getOperand(0)->getName()+
2803 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002804
2805 // If the multiply type is not the same as the source type, sign extend
2806 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002807 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002808 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002810 Instruction::CastOps opcode =
2811 (SrcBits == DstBits ? Instruction::BitCast :
2812 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813 V = InsertCastBefore(opcode, V, I.getType(), I);
2814 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002815
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002816 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002817 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002818 }
2819 }
2820 }
2821
Chris Lattner7e708292002-06-25 16:13:24 +00002822 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002823}
2824
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002825Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826 bool Changed = SimplifyCommutative(I);
2827 Value *Op0 = I.getOperand(0);
2828
2829 // Simplify mul instructions with a constant RHS...
2830 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2833 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834 if (Op1F->isExactlyValue(1.0))
2835 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2836 } else if (isa<VectorType>(Op1->getType())) {
2837 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838 // As above, vector X*splat(1.0) -> X in all defined cases.
2839 if (Constant *Splat = Op1V->getSplatValue()) {
2840 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841 if (F->isExactlyValue(1.0))
2842 return ReplaceInstUsesWith(I, Op0);
2843 }
2844 }
2845 }
2846
2847 // Try to fold constant mul into select arguments.
2848 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850 return R;
2851
2852 if (isa<PHINode>(Op0))
2853 if (Instruction *NV = FoldOpIntoPhi(I))
2854 return NV;
2855 }
2856
Owen Andersond672ecb2009-07-03 00:17:18 +00002857 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2858 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002859 return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861 return Changed ? &I : 0;
2862}
2863
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002864/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865/// instruction.
2866bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868
2869 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870 int NonNullOperand = -1;
2871 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872 if (ST->isNullValue())
2873 NonNullOperand = 2;
2874 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876 if (ST->isNullValue())
2877 NonNullOperand = 1;
2878
2879 if (NonNullOperand == -1)
2880 return false;
2881
2882 Value *SelectCond = SI->getOperand(0);
2883
2884 // Change the div/rem to use 'Y' instead of the select.
2885 I.setOperand(1, SI->getOperand(NonNullOperand));
2886
2887 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888 // problem. However, the select, or the condition of the select may have
2889 // multiple uses. Based on our knowledge that the operand must be non-zero,
2890 // propagate the known value for the select into other uses of it, and
2891 // propagate a known value of the condition into its other users.
2892
2893 // If the select and condition only have a single use, don't bother with this,
2894 // early exit.
2895 if (SI->use_empty() && SelectCond->hasOneUse())
2896 return true;
2897
2898 // Scan the current block backward, looking for other uses of SI.
2899 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900
2901 while (BBI != BBFront) {
2902 --BBI;
2903 // If we found a call to a function, we can't assume it will return, so
2904 // information from below it cannot be propagated above it.
2905 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906 break;
2907
2908 // Replace uses of the select or its condition with the known values.
2909 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910 I != E; ++I) {
2911 if (*I == SI) {
2912 *I = SI->getOperand(NonNullOperand);
2913 AddToWorkList(BBI);
2914 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002915 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2916 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002917 AddToWorkList(BBI);
2918 }
2919 }
2920
2921 // If we past the instruction, quit looking for it.
2922 if (&*BBI == SI)
2923 SI = 0;
2924 if (&*BBI == SelectCond)
2925 SelectCond = 0;
2926
2927 // If we ran out of things to eliminate, break out of the loop.
2928 if (SelectCond == 0 && SI == 0)
2929 break;
2930
2931 }
2932 return true;
2933}
2934
2935
Reid Spencer1628cec2006-10-26 06:15:43 +00002936/// This function implements the transforms on div instructions that work
2937/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938/// used by the visitors to those instructions.
2939/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002940Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002942
Chris Lattner50b2ca42008-02-19 06:12:18 +00002943 // undef / X -> 0 for integer.
2944 // undef / X -> undef for FP (the undef could be a snan).
2945 if (isa<UndefValue>(Op0)) {
2946 if (Op0->getType()->isFPOrFPVector())
2947 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002948 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002949 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002950
2951 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002952 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002953 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002954
Reid Spencer1628cec2006-10-26 06:15:43 +00002955 return 0;
2956}
Misha Brukmanfd939082005-04-21 23:48:37 +00002957
Reid Spencer1628cec2006-10-26 06:15:43 +00002958/// This function implements the transforms common to both integer division
2959/// instructions (udiv and sdiv). It is called by the visitors to those integer
2960/// division instructions.
2961/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002962Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002965 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002966 if (Op0 == Op1) {
2967 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002968 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002969 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002970 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002971 }
2972
Owen Andersond672ecb2009-07-03 00:17:18 +00002973 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002974 return ReplaceInstUsesWith(I, CI);
2975 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002976
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 if (Instruction *Common = commonDivTransforms(I))
2978 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002979
2980 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981 // This does not apply for fdiv.
2982 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002984
2985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986 // div X, 1 == X
2987 if (RHS->equalsInt(1))
2988 return ReplaceInstUsesWith(I, Op0);
2989
2990 // (X / C1) / C2 -> X / (C1*C2)
2991 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002994 if (MultiplyOverflows(RHS, LHSRHS,
2995 I.getOpcode()==Instruction::SDiv, Context))
2996 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002997 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002998 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002999 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003000 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003001
Reid Spencerbca0e382007-03-23 20:05:17 +00003002 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3004 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3005 return R;
3006 if (isa<PHINode>(Op0))
3007 if (Instruction *NV = FoldOpIntoPhi(I))
3008 return NV;
3009 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003010 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003011
Chris Lattnera2881962003-02-18 19:28:33 +00003012 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003013 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003014 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003015 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003016
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003017 // It can't be division by zero, hence it must be division by one.
3018 if (I.getType() == Type::Int1Ty)
3019 return ReplaceInstUsesWith(I, Op0);
3020
Nick Lewycky895f0852008-11-27 20:21:08 +00003021 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3022 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3023 // div X, 1 == X
3024 if (X->isOne())
3025 return ReplaceInstUsesWith(I, Op0);
3026 }
3027
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 return 0;
3029}
3030
3031Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3032 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3033
3034 // Handle the integer div common cases
3035 if (Instruction *Common = commonIDivTransforms(I))
3036 return Common;
3037
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003039 // X udiv C^2 -> X >> C
3040 // Check to see if this is an unsigned division with an exact power of 2,
3041 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003042 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003043 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003044 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003045
3046 // X udiv C, where C >= signbit
3047 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003048 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3049 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003050 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003051 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3052 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003053 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003054 }
3055
3056 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003057 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003058 if (RHSI->getOpcode() == Instruction::Shl &&
3059 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003060 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003061 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003063 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003064 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003065 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003067 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003069 }
3070 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003071 }
3072
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3074 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003075 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003078 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003079 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003080 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003083 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003084 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 Op0, TC, SI->getName()+".t");
3086 TSI = InsertNewInstBefore(TSI, I);
3087
3088 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003089 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003090 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003091 Op0, FC, SI->getName()+".f");
3092 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003093
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003095 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003096 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003097 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003098 return 0;
3099}
3100
Reid Spencer1628cec2006-10-26 06:15:43 +00003101Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
3104 // Handle the integer div common cases
3105 if (Instruction *Common = commonIDivTransforms(I))
3106 return Common;
3107
3108 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3109 // sdiv X, -1 == -X
3110 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003112 }
3113
3114 // If the sign bits of both operands are zero (i.e. we can prove they are
3115 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003116 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003117 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003118 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003119 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003120 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003121 }
3122 }
3123
3124 return 0;
3125}
3126
3127Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3128 return commonDivTransforms(I);
3129}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003130
Reid Spencer0a783f72006-11-02 01:53:59 +00003131/// This function implements the transforms on rem instructions that work
3132/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3133/// is used by the visitors to those instructions.
3134/// @brief Transforms common to all three rem instructions
3135Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003137
Chris Lattner50b2ca42008-02-19 06:12:18 +00003138 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3139 if (I.getType()->isFPOrFPVector())
3140 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003141 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003142 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003143 if (isa<UndefValue>(Op1))
3144 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003145
3146 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003147 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3148 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003149
Reid Spencer0a783f72006-11-02 01:53:59 +00003150 return 0;
3151}
3152
3153/// This function implements the transforms common to both integer remainder
3154/// instructions (urem and srem). It is called by the visitors to those integer
3155/// remainder instructions.
3156/// @brief Common integer remainder transforms
3157Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160 if (Instruction *common = commonRemTransforms(I))
3161 return common;
3162
Dale Johannesened6af242009-01-21 00:35:19 +00003163 // 0 % X == 0 for integer, we don't need to preserve faults!
3164 if (Constant *LHS = dyn_cast<Constant>(Op0))
3165 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003166 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003167
Chris Lattner857e8cd2004-12-12 21:48:58 +00003168 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003169 // X % 0 == undef, we don't need to preserve faults!
3170 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003171 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003172
Chris Lattnera2881962003-02-18 19:28:33 +00003173 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003174 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003175
Chris Lattner97943922006-02-28 05:49:21 +00003176 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3177 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3178 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3179 return R;
3180 } else if (isa<PHINode>(Op0I)) {
3181 if (Instruction *NV = FoldOpIntoPhi(I))
3182 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003183 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003184
3185 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003186 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003187 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003188 }
Chris Lattnera2881962003-02-18 19:28:33 +00003189 }
3190
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 return 0;
3192}
3193
3194Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3196
3197 if (Instruction *common = commonIRemTransforms(I))
3198 return common;
3199
3200 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3201 // X urem C^2 -> X and C
3202 // Check to see if this is an unsigned remainder with an exact power of 2,
3203 // if so, convert to a bitwise and.
3204 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003205 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003206 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 }
3208
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003209 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3211 if (RHSI->getOpcode() == Instruction::Shl &&
3212 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003213 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003214 Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003215 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003216 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003217 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003218 }
3219 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003220 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003221
Reid Spencer0a783f72006-11-02 01:53:59 +00003222 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3223 // where C1&C2 are powers of two.
3224 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3225 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3226 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3227 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003228 if ((STO->getValue().isPowerOf2()) &&
3229 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003231 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3232 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003234 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3235 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003236 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 }
3238 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003239 }
3240
Chris Lattner3f5b8772002-05-06 16:14:14 +00003241 return 0;
3242}
3243
Reid Spencer0a783f72006-11-02 01:53:59 +00003244Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3246
Dan Gohmancff55092007-11-05 23:16:33 +00003247 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003248 if (Instruction *common = commonIRemTransforms(I))
3249 return common;
3250
Owen Andersond672ecb2009-07-03 00:17:18 +00003251 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003252 if (!isa<Constant>(RHSNeg) ||
3253 (isa<ConstantInt>(RHSNeg) &&
3254 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003255 // X % -Y -> X % Y
3256 AddUsesToWorkList(I);
3257 I.setOperand(1, RHSNeg);
3258 return &I;
3259 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003260
Dan Gohmancff55092007-11-05 23:16:33 +00003261 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003262 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003263 if (I.getType()->isInteger()) {
3264 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3265 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3266 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003267 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003268 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003269 }
3270
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003271 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003272 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3273 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003274
Nick Lewycky9dce8732008-12-20 16:48:00 +00003275 bool hasNegative = false;
3276 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3277 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3278 if (RHS->getValue().isNegative())
3279 hasNegative = true;
3280
3281 if (hasNegative) {
3282 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003283 for (unsigned i = 0; i != VWidth; ++i) {
3284 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3285 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003286 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003287 else
3288 Elts[i] = RHS;
3289 }
3290 }
3291
Owen Andersond672ecb2009-07-03 00:17:18 +00003292 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003293 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003294 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003295 I.setOperand(1, NewRHSV);
3296 return &I;
3297 }
3298 }
3299 }
3300
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 return 0;
3302}
3303
3304Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003305 return commonRemTransforms(I);
3306}
3307
Chris Lattner457dd822004-06-09 07:59:58 +00003308// isOneBitSet - Return true if there is exactly one bit set in the specified
3309// constant.
3310static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003311 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003312}
3313
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003314// isHighOnes - Return true if the constant is of the form 1+0+.
3315// This is the same as lowones(~X).
3316static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003317 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003318}
3319
Reid Spencere4d87aa2006-12-23 06:05:41 +00003320/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003321/// are carefully arranged to allow folding of expressions such as:
3322///
3323/// (A < B) | (A > B) --> (A != B)
3324///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325/// Note that this is only valid if the first and second predicates have the
3326/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003327///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328/// Three bits are used to represent the condition, as follows:
3329/// 0 A > B
3330/// 1 A == B
3331/// 2 A < B
3332///
3333/// <=> Value Definition
3334/// 000 0 Always false
3335/// 001 1 A > B
3336/// 010 2 A == B
3337/// 011 3 A >= B
3338/// 100 4 A < B
3339/// 101 5 A != B
3340/// 110 6 A <= B
3341/// 111 7 Always true
3342///
3343static unsigned getICmpCode(const ICmpInst *ICI) {
3344 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003345 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003346 case ICmpInst::ICMP_UGT: return 1; // 001
3347 case ICmpInst::ICMP_SGT: return 1; // 001
3348 case ICmpInst::ICMP_EQ: return 2; // 010
3349 case ICmpInst::ICMP_UGE: return 3; // 011
3350 case ICmpInst::ICMP_SGE: return 3; // 011
3351 case ICmpInst::ICMP_ULT: return 4; // 100
3352 case ICmpInst::ICMP_SLT: return 4; // 100
3353 case ICmpInst::ICMP_NE: return 5; // 101
3354 case ICmpInst::ICMP_ULE: return 6; // 110
3355 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003356 // True -> 7
3357 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003359 return 0;
3360 }
3361}
3362
Evan Cheng8db90722008-10-14 17:15:11 +00003363/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3364/// predicate into a three bit mask. It also returns whether it is an ordered
3365/// predicate by reference.
3366static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3367 isOrdered = false;
3368 switch (CC) {
3369 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3370 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003371 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3372 case FCmpInst::FCMP_UGT: return 1; // 001
3373 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3374 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003375 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3376 case FCmpInst::FCMP_UGE: return 3; // 011
3377 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3378 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003379 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3380 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003381 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3382 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003383 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003384 default:
3385 // Not expecting FCMP_FALSE and FCMP_TRUE;
3386 assert(0 && "Unexpected FCmp predicate!");
3387 return 0;
3388 }
3389}
3390
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391/// getICmpValue - This is the complement of getICmpCode, which turns an
3392/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003393/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003394/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003395static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003396 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 switch (code) {
3398 default: assert(0 && "Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003399 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 case 1:
3401 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003402 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 else
Owen Anderson333c4002009-07-09 23:48:35 +00003404 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3405 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 case 3:
3407 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003408 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 else
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 case 4:
3412 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003413 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 else
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3416 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 case 6:
3418 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003419 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420 else
Owen Anderson333c4002009-07-09 23:48:35 +00003421 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003422 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003423 }
3424}
3425
Evan Cheng8db90722008-10-14 17:15:11 +00003426/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3427/// opcode and two operands into either a FCmp instruction. isordered is passed
3428/// in to determine which kind of predicate to use in the new fcmp instruction.
3429static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003430 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003431 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003432 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003433 case 0:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003436 else
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003438 case 1:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 else
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003443 case 2:
3444 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003446 else
Owen Anderson333c4002009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003448 case 3:
3449 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003450 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003451 else
Owen Anderson333c4002009-07-09 23:48:35 +00003452 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 case 4:
3454 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003455 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 else
Owen Anderson333c4002009-07-09 23:48:35 +00003457 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003458 case 5:
3459 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003460 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003461 else
Owen Anderson333c4002009-07-09 23:48:35 +00003462 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003463 case 6:
3464 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003465 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003466 else
Owen Anderson333c4002009-07-09 23:48:35 +00003467 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003468 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003469 }
3470}
3471
Chris Lattnerb9553d62008-11-16 04:55:20 +00003472/// PredicatesFoldable - Return true if both predicates match sign or if at
3473/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3475 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003476 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3477 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478}
3479
3480namespace {
3481// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3482struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 InstCombiner &IC;
3484 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003485 ICmpInst::Predicate pred;
3486 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3487 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3488 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3491 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003492 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3493 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 return false;
3495 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003496 Instruction *apply(Instruction &Log) const {
3497 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3498 if (ICI->getOperand(0) != LHS) {
3499 assert(ICI->getOperand(1) == LHS);
3500 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 }
3502
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003503 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003505 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 unsigned Code;
3507 switch (Log.getOpcode()) {
3508 case Instruction::And: Code = LHSCode & RHSCode; break;
3509 case Instruction::Or: Code = LHSCode | RHSCode; break;
3510 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003511 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003512 }
3513
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003514 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3515 ICmpInst::isSignedPredicate(ICI->getPredicate());
3516
Owen Andersond672ecb2009-07-03 00:17:18 +00003517 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003518 if (Instruction *I = dyn_cast<Instruction>(RV))
3519 return I;
3520 // Otherwise, it's a constant boolean value...
3521 return IC.ReplaceInstUsesWith(Log, RV);
3522 }
3523};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003524} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003525
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003526// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3527// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003528// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003529Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003530 ConstantInt *OpRHS,
3531 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 BinaryOperator &TheAnd) {
3533 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003534 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003535 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003536 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003537
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 switch (Op->getOpcode()) {
3539 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003540 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003542 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003544 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003545 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 }
3547 break;
3548 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003549 if (Together == AndRHS) // (X | C) & C --> C
3550 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003551
Chris Lattner6e7ba452005-01-01 16:22:27 +00003552 if (Op->hasOneUse() && Together != OpRHS) {
3553 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003555 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003556 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003557 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003558 }
3559 break;
3560 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003561 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003562 // Adding a one to a single bit bit-field should be turned into an XOR
3563 // of the bit. First thing to check is to see if this AND is with a
3564 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003565 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566
3567 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003568 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 // Ok, at this point, we know that we are masking the result of the
3570 // ADD down to exactly one bit. If the constant we are adding has
3571 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003572 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003573
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574 // Check to see if any bits below the one bit set in AndRHSV are set.
3575 if ((AddRHS & (AndRHSV-1)) == 0) {
3576 // If not, the only thing that can effect the output of the AND is
3577 // the bit specified by AndRHSV. If that bit is set, the effect of
3578 // the XOR is to toggle the bit. If it is clear, then the ADD has
3579 // no effect.
3580 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3581 TheAnd.setOperand(0, X);
3582 return &TheAnd;
3583 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003584 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003585 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003586 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003587 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003588 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003589 }
3590 }
3591 }
3592 }
3593 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003594
3595 case Instruction::Shl: {
3596 // We know that the AND will not produce any of the bits shifted in, so if
3597 // the anded constant includes them, clear them now!
3598 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003602 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003603
Zhou Sheng290bec52007-03-29 08:15:12 +00003604 if (CI->getValue() == ShlMask) {
3605 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003606 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3607 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003608 TheAnd.setOperand(1, CI);
3609 return &TheAnd;
3610 }
3611 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003612 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003613 case Instruction::LShr:
3614 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003615 // We know that the AND will not produce any of the bits shifted in, so if
3616 // the anded constant includes them, clear them now! This only applies to
3617 // unsigned shifts, because a signed shr may bring in set bits!
3618 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003620 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003621 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003622 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003623
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 if (CI->getValue() == ShrMask) {
3625 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003626 return ReplaceInstUsesWith(TheAnd, Op);
3627 } else if (CI != AndRHS) {
3628 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3629 return &TheAnd;
3630 }
3631 break;
3632 }
3633 case Instruction::AShr:
3634 // Signed shr.
3635 // See if this is shifting in some sign extension, then masking it out
3636 // with an and.
3637 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003638 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003639 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003640 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003641 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003642 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003643 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003644 // Make the argument unsigned.
3645 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003646 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003647 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003648 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003649 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003650 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003651 }
3652 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003653 }
3654 return 0;
3655}
3656
Chris Lattner8b170942002-08-09 23:47:40 +00003657
Chris Lattnera96879a2004-09-29 17:40:11 +00003658/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3661/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003662/// insert new instructions.
3663Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 bool isSigned, bool Inside,
3665 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003666 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003667 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003668 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669
Chris Lattnera96879a2004-09-29 17:40:11 +00003670 if (Inside) {
3671 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003673
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003676 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003678 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 }
3680
3681 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003682 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003683 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003684 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003685 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003687 }
3688
3689 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003690 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003691
Reid Spencere4e40032007-03-21 23:19:50 +00003692 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003693 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003694 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 ICmpInst::Predicate pred = (isSigned ?
3696 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003697 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003699
Reid Spencere4e40032007-03-21 23:19:50 +00003700 // Emit V-Lo >u Hi-1-Lo
3701 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003702 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003703 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003704 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003705 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003706 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003707}
3708
Chris Lattner7203e152005-09-18 07:22:02 +00003709// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3710// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3711// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3712// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003713static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003714 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003715 uint32_t BitWidth = Val->getType()->getBitWidth();
3716 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003717
3718 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003719 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003720 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003721 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003722 return true;
3723}
3724
Chris Lattner7203e152005-09-18 07:22:02 +00003725/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3726/// where isSub determines whether the operator is a sub. If we can fold one of
3727/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003728///
3729/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3730/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3732///
3733/// return (A +/- B).
3734///
3735Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003736 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003737 Instruction &I) {
3738 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3739 if (!LHSI || LHSI->getNumOperands() != 2 ||
3740 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3741
3742 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3743
3744 switch (LHSI->getOpcode()) {
3745 default: return 0;
3746 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003747 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003748 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003749 if ((Mask->getValue().countLeadingZeros() +
3750 Mask->getValue().countPopulation()) ==
3751 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003752 break;
3753
3754 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3755 // part, we don't need any explicit masks to take them out of A. If that
3756 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003757 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003758 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003759 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003760 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003761 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003762 break;
3763 }
3764 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003765 return 0;
3766 case Instruction::Or:
3767 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003768 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003769 if ((Mask->getValue().countLeadingZeros() +
3770 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003771 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003772 break;
3773 return 0;
3774 }
3775
3776 Instruction *New;
3777 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003778 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003779 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003780 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003781 return InsertNewInstBefore(New, I);
3782}
3783
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003784/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3785Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3786 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003787 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003788 ConstantInt *LHSCst, *RHSCst;
3789 ICmpInst::Predicate LHSCC, RHSCC;
3790
Chris Lattnerea065fb2008-11-16 05:10:52 +00003791 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003792 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3793 m_ConstantInt(LHSCst)), *Context) ||
3794 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3795 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003797
3798 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3799 // where C is a power of 2
3800 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3801 LHSCst->getValue().isPowerOf2()) {
3802 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3803 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003804 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003805 }
3806
3807 // From here on, we only handle:
3808 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3809 if (Val != Val2) return 0;
3810
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3812 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3813 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3814 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3815 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3816 return 0;
3817
3818 // We can't fold (ugt x, C) & (sgt x, C2).
3819 if (!PredicatesFoldable(LHSCC, RHSCC))
3820 return 0;
3821
3822 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003823 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003824 if (ICmpInst::isSignedPredicate(LHSCC) ||
3825 (ICmpInst::isEquality(LHSCC) &&
3826 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003827 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003828 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003829 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3830
3831 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 std::swap(LHS, RHS);
3833 std::swap(LHSCst, RHSCst);
3834 std::swap(LHSCC, RHSCC);
3835 }
3836
3837 // At this point, we know we have have two icmp instructions
3838 // comparing a value against two constants and and'ing the result
3839 // together. Because of the above check, we know that we only have
3840 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3841 // (from the FoldICmpLogical check above), that the two constants
3842 // are not equal and that the larger constant is on the RHS
3843 assert(LHSCst != RHSCst && "Compares not folded above?");
3844
3845 switch (LHSCC) {
3846 default: assert(0 && "Unknown integer condition code!");
3847 case ICmpInst::ICMP_EQ:
3848 switch (RHSCC) {
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3851 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3852 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003853 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3855 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3856 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3857 return ReplaceInstUsesWith(I, LHS);
3858 }
3859 case ICmpInst::ICMP_NE:
3860 switch (RHSCC) {
3861 default: assert(0 && "Unknown integer condition code!");
3862 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003863 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003864 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003865 break; // (X != 13 & X u< 15) -> no change
3866 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003867 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003868 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003869 break; // (X != 13 & X s< 15) -> no change
3870 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3871 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3872 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3873 return ReplaceInstUsesWith(I, RHS);
3874 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003875 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3876 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3878 Val->getName()+".off");
3879 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003880 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003881 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 }
3883 break; // (X != 13 & X != 15) -> no change
3884 }
3885 break;
3886 case ICmpInst::ICMP_ULT:
3887 switch (RHSCC) {
3888 default: assert(0 && "Unknown integer condition code!");
3889 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3890 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003891 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003892 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3895 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3896 return ReplaceInstUsesWith(I, LHS);
3897 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3898 break;
3899 }
3900 break;
3901 case ICmpInst::ICMP_SLT:
3902 switch (RHSCC) {
3903 default: assert(0 && "Unknown integer condition code!");
3904 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3905 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003906 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3908 break;
3909 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3910 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3911 return ReplaceInstUsesWith(I, LHS);
3912 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3913 break;
3914 }
3915 break;
3916 case ICmpInst::ICMP_UGT:
3917 switch (RHSCC) {
3918 default: assert(0 && "Unknown integer condition code!");
3919 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3920 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3921 return ReplaceInstUsesWith(I, RHS);
3922 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3923 break;
3924 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003925 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003926 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003927 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003928 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003929 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3930 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3932 break;
3933 }
3934 break;
3935 case ICmpInst::ICMP_SGT:
3936 switch (RHSCC) {
3937 default: assert(0 && "Unknown integer condition code!");
3938 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3939 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3940 return ReplaceInstUsesWith(I, RHS);
3941 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3942 break;
3943 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003944 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003945 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003947 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003948 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3949 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003950 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3951 break;
3952 }
3953 break;
3954 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955
3956 return 0;
3957}
3958
3959
Chris Lattner7e708292002-06-25 16:13:24 +00003960Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003961 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003963
Chris Lattnere87597f2004-10-16 18:11:37 +00003964 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003965 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003966
Chris Lattner6e7ba452005-01-01 16:22:27 +00003967 // and X, X = X
3968 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003969 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003970
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003971 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003972 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003973 if (SimplifyDemandedInstructionBits(I))
3974 return &I;
3975 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003976 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003977 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003978 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003979 } else if (isa<ConstantAggregateZero>(Op1)) {
3980 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003981 }
3982 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003983
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003984 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003985 const APInt& AndRHSMask = AndRHS->getValue();
3986 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003987
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003988 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003989 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003990 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003991 Value *Op0LHS = Op0I->getOperand(0);
3992 Value *Op0RHS = Op0I->getOperand(1);
3993 switch (Op0I->getOpcode()) {
3994 case Instruction::Xor:
3995 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003996 // If the mask is only needed on one incoming arm, push it up.
3997 if (Op0I->hasOneUse()) {
3998 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3999 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004000 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004001 Op0RHS->getName()+".masked");
4002 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004003 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004004 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004005 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004006 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004007 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4008 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004009 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004010 Op0LHS->getName()+".masked");
4011 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004013 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4014 }
4015 }
4016
Chris Lattner6e7ba452005-01-01 16:22:27 +00004017 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004018 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004019 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4020 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4021 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4022 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004023 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004024 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 break;
4027
4028 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004029 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4030 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4031 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4032 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004034
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004035 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4036 // has 1's for all bits that the subtraction with A might affect.
4037 if (Op0I->hasOneUse()) {
4038 uint32_t BitWidth = AndRHSMask.getBitWidth();
4039 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4040 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4041
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004042 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004043 if (!(A && A->isZero()) && // avoid infinite recursion.
4044 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004045 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4046 InsertNewInstBefore(NewNeg, I);
4047 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4048 }
4049 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004050 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004051
4052 case Instruction::Shl:
4053 case Instruction::LShr:
4054 // (1 << x) & 1 --> zext(x == 0)
4055 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004056 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004057 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4058 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004059 InsertNewInstBefore(NewICmp, I);
4060 return new ZExtInst(NewICmp, I.getType());
4061 }
4062 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004063 }
4064
Chris Lattner58403262003-07-23 19:25:52 +00004065 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004066 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004067 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004068 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004069 // If this is an integer truncation or change from signed-to-unsigned, and
4070 // if the source is an and/or with immediate, transform it. This
4071 // frequently occurs for bitfield accesses.
4072 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004073 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004074 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004075 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004076 if (CastOp->getOpcode() == Instruction::And) {
4077 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004078 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4079 // This will fold the two constants together, which may allow
4080 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004081 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004082 CastOp->getOperand(0), I.getType(),
4083 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004084 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004085 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004086 Constant *C3 =
4087 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4088 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004090 } else if (CastOp->getOpcode() == Instruction::Or) {
4091 // Change: and (cast (or X, C1) to T), C2
4092 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004093 Constant *C3 =
4094 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4095 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4096 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004097 return ReplaceInstUsesWith(I, AndRHS);
4098 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004099 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004100 }
Chris Lattner06782f82003-07-23 19:36:21 +00004101 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004102
4103 // Try to fold constant and into select arguments.
4104 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004106 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004107 if (isa<PHINode>(Op0))
4108 if (Instruction *NV = FoldOpIntoPhi(I))
4109 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004110 }
4111
Owen Andersond672ecb2009-07-03 00:17:18 +00004112 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4113 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004114
Chris Lattner5b62aa72004-06-18 06:07:51 +00004115 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004116 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004117
Misha Brukmancb6267b2004-07-30 12:50:08 +00004118 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004119 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004121 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004122 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004123 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004124 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004125
4126 {
Chris Lattner003b6202007-06-15 05:58:24 +00004127 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004128 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004129 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4130 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004131
4132 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004133 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004134 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004136 }
4137 }
4138
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004139 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004140 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4141 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004142
4143 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004144 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004145 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004147 }
4148 }
Chris Lattner64daab52006-04-01 08:03:55 +00004149
4150 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004151 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004152 if (A == Op1) { // (A^B)&A -> A&(A^B)
4153 I.swapOperands(); // Simplify below
4154 std::swap(Op0, Op1);
4155 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4156 cast<BinaryOperator>(Op0)->swapOperands();
4157 I.swapOperands(); // Simplify below
4158 std::swap(Op0, Op1);
4159 }
4160 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004161
Chris Lattner64daab52006-04-01 08:03:55 +00004162 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004163 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004164 if (B == Op0) { // B&(A^B) -> B&(B^A)
4165 cast<BinaryOperator>(Op1)->swapOperands();
4166 std::swap(A, B);
4167 }
4168 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004169 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004170 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004171 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004172 }
4173 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004174
4175 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004176 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4177 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004178 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004179 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4180 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004181 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004182 }
4183
Reid Spencere4d87aa2006-12-23 06:05:41 +00004184 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4185 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004186 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004187 return R;
4188
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004189 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4190 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4191 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004192 }
4193
Chris Lattner6fc205f2006-05-05 06:39:07 +00004194 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004195 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4196 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4197 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4198 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004199 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004200 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004201 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4202 I.getType(), TD) &&
4203 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4204 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004205 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004206 Op1C->getOperand(0),
4207 I.getName());
4208 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004209 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004210 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004211 }
Chris Lattnere511b742006-11-14 07:46:50 +00004212
4213 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004214 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4215 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4216 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004217 SI0->getOperand(1) == SI1->getOperand(1) &&
4218 (SI0->hasOneUse() || SI1->hasOneUse())) {
4219 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004220 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004221 SI1->getOperand(0),
4222 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004223 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004224 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004225 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004226 }
4227
Evan Cheng8db90722008-10-14 17:15:11 +00004228 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004229 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4230 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4231 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004232 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004234 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236 // If either of the constants are nans, then the whole thing returns
4237 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004238 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004239 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004240 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4241 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004242 }
Evan Cheng8db90722008-10-14 17:15:11 +00004243 } else {
4244 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4245 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004246 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4247 m_Value(Op0RHS)), *Context) &&
4248 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4249 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004250 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4251 // Swap RHS operands to match LHS.
4252 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4253 std::swap(Op1LHS, Op1RHS);
4254 }
Evan Cheng8db90722008-10-14 17:15:11 +00004255 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4256 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4257 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004258 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4259 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004260 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4261 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004262 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004263 else if (Op0CC == FCmpInst::FCMP_TRUE)
4264 return ReplaceInstUsesWith(I, Op1);
4265 else if (Op1CC == FCmpInst::FCMP_TRUE)
4266 return ReplaceInstUsesWith(I, Op0);
4267 bool Op0Ordered;
4268 bool Op1Ordered;
4269 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4270 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4271 if (Op1Pred == 0) {
4272 std::swap(Op0, Op1);
4273 std::swap(Op0Pred, Op1Pred);
4274 std::swap(Op0Ordered, Op1Ordered);
4275 }
4276 if (Op0Pred == 0) {
4277 // uno && ueq -> uno && (uno || eq) -> ueq
4278 // ord && olt -> ord && (ord && lt) -> olt
4279 if (Op0Ordered == Op1Ordered)
4280 return ReplaceInstUsesWith(I, Op1);
4281 // uno && oeq -> uno && (ord && eq) -> false
4282 // uno && ord -> false
4283 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004284 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004285 // ord && ueq -> ord && (uno || eq) -> oeq
4286 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004287 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004288 }
4289 }
4290 }
4291 }
Chris Lattner99c65742007-10-24 05:38:08 +00004292 }
4293 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004294
Chris Lattner7e708292002-06-25 16:13:24 +00004295 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004296}
4297
Chris Lattner8c34cd22008-10-05 02:13:19 +00004298/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4299/// capable of providing pieces of a bswap. The subexpression provides pieces
4300/// of a bswap if it is proven that each of the non-zero bytes in the output of
4301/// the expression came from the corresponding "byte swapped" byte in some other
4302/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4303/// we know that the expression deposits the low byte of %X into the high byte
4304/// of the bswap result and that all other bytes are zero. This expression is
4305/// accepted, the high byte of ByteValues is set to X to indicate a correct
4306/// match.
4307///
4308/// This function returns true if the match was unsuccessful and false if so.
4309/// On entry to the function the "OverallLeftShift" is a signed integer value
4310/// indicating the number of bytes that the subexpression is later shifted. For
4311/// example, if the expression is later right shifted by 16 bits, the
4312/// OverallLeftShift value would be -2 on entry. This is used to specify which
4313/// byte of ByteValues is actually being set.
4314///
4315/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4316/// byte is masked to zero by a user. For example, in (X & 255), X will be
4317/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4318/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4319/// always in the local (OverallLeftShift) coordinate space.
4320///
4321static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4322 SmallVector<Value*, 8> &ByteValues) {
4323 if (Instruction *I = dyn_cast<Instruction>(V)) {
4324 // If this is an or instruction, it may be an inner node of the bswap.
4325 if (I->getOpcode() == Instruction::Or) {
4326 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4327 ByteValues) ||
4328 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4329 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004330 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004331
4332 // If this is a logical shift by a constant multiple of 8, recurse with
4333 // OverallLeftShift and ByteMask adjusted.
4334 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4335 unsigned ShAmt =
4336 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4337 // Ensure the shift amount is defined and of a byte value.
4338 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4339 return true;
4340
4341 unsigned ByteShift = ShAmt >> 3;
4342 if (I->getOpcode() == Instruction::Shl) {
4343 // X << 2 -> collect(X, +2)
4344 OverallLeftShift += ByteShift;
4345 ByteMask >>= ByteShift;
4346 } else {
4347 // X >>u 2 -> collect(X, -2)
4348 OverallLeftShift -= ByteShift;
4349 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004350 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004351 }
4352
4353 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4354 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4355
4356 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4357 ByteValues);
4358 }
4359
4360 // If this is a logical 'and' with a mask that clears bytes, clear the
4361 // corresponding bytes in ByteMask.
4362 if (I->getOpcode() == Instruction::And &&
4363 isa<ConstantInt>(I->getOperand(1))) {
4364 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4365 unsigned NumBytes = ByteValues.size();
4366 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4367 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4368
4369 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4370 // If this byte is masked out by a later operation, we don't care what
4371 // the and mask is.
4372 if ((ByteMask & (1 << i)) == 0)
4373 continue;
4374
4375 // If the AndMask is all zeros for this byte, clear the bit.
4376 APInt MaskB = AndMask & Byte;
4377 if (MaskB == 0) {
4378 ByteMask &= ~(1U << i);
4379 continue;
4380 }
4381
4382 // If the AndMask is not all ones for this byte, it's not a bytezap.
4383 if (MaskB != Byte)
4384 return true;
4385
4386 // Otherwise, this byte is kept.
4387 }
4388
4389 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4390 ByteValues);
4391 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392 }
4393
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4395 // the input value to the bswap. Some observations: 1) if more than one byte
4396 // is demanded from this input, then it could not be successfully assembled
4397 // into a byteswap. At least one of the two bytes would not be aligned with
4398 // their ultimate destination.
4399 if (!isPowerOf2_32(ByteMask)) return true;
4400 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004401
Chris Lattner8c34cd22008-10-05 02:13:19 +00004402 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4403 // is demanded, it needs to go into byte 0 of the result. This means that the
4404 // byte needs to be shifted until it lands in the right byte bucket. The
4405 // shift amount depends on the position: if the byte is coming from the high
4406 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4407 // low part, it must be shifted left.
4408 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4409 if (InputByteNo < ByteValues.size()/2) {
4410 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411 return true;
4412 } else {
4413 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4414 return true;
4415 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004416
4417 // If the destination byte value is already defined, the values are or'd
4418 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004419 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004420 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004421 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004422 return false;
4423}
4424
4425/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4426/// If so, insert the new bswap intrinsic and return it.
4427Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004428 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004429 if (!ITy || ITy->getBitWidth() % 16 ||
4430 // ByteMask only allows up to 32-byte values.
4431 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004432 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433
4434 /// ByteValues - For each byte of the result, we keep track of which value
4435 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004436 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004437 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438
4439 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004440 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4441 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442 return 0;
4443
4444 // Check to see if all of the bytes come from the same value.
4445 Value *V = ByteValues[0];
4446 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4447
4448 // Check to make sure that all of the bytes come from the same value.
4449 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4450 if (ByteValues[i] != V)
4451 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004452 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004453 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004454 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004455 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004456}
4457
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004458/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4459/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4460/// we can simplify this expression to "cond ? C : D or B".
4461static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004462 Value *C, Value *D,
4463 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004464 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004465 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004466 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004467 return 0;
4468
Chris Lattnera6a474d2008-11-16 04:26:55 +00004469 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004470 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004471 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004472 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004473 return SelectInst::Create(Cond, C, B);
4474 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004475 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004476 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004477 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004478 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004479 return 0;
4480}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004481
Chris Lattner69d4ced2008-11-16 05:20:07 +00004482/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4483Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4484 ICmpInst *LHS, ICmpInst *RHS) {
4485 Value *Val, *Val2;
4486 ConstantInt *LHSCst, *RHSCst;
4487 ICmpInst::Predicate LHSCC, RHSCC;
4488
4489 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004490 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4491 m_ConstantInt(LHSCst)), *Context) ||
4492 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4493 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004494 return 0;
4495
4496 // From here on, we only handle:
4497 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4498 if (Val != Val2) return 0;
4499
4500 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4501 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4502 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4503 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4504 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4505 return 0;
4506
4507 // We can't fold (ugt x, C) | (sgt x, C2).
4508 if (!PredicatesFoldable(LHSCC, RHSCC))
4509 return 0;
4510
4511 // Ensure that the larger constant is on the RHS.
4512 bool ShouldSwap;
4513 if (ICmpInst::isSignedPredicate(LHSCC) ||
4514 (ICmpInst::isEquality(LHSCC) &&
4515 ICmpInst::isSignedPredicate(RHSCC)))
4516 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4517 else
4518 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4519
4520 if (ShouldSwap) {
4521 std::swap(LHS, RHS);
4522 std::swap(LHSCst, RHSCst);
4523 std::swap(LHSCC, RHSCC);
4524 }
4525
4526 // At this point, we know we have have two icmp instructions
4527 // comparing a value against two constants and or'ing the result
4528 // together. Because of the above check, we know that we only have
4529 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4530 // FoldICmpLogical check above), that the two constants are not
4531 // equal.
4532 assert(LHSCst != RHSCst && "Compares not folded above?");
4533
4534 switch (LHSCC) {
4535 default: assert(0 && "Unknown integer condition code!");
4536 case ICmpInst::ICMP_EQ:
4537 switch (RHSCC) {
4538 default: assert(0 && "Unknown integer condition code!");
4539 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004540 if (LHSCst == SubOne(RHSCst, Context)) {
4541 // (X == 13 | X == 14) -> X-13 <u 2
4542 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004543 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4544 Val->getName()+".off");
4545 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004546 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004547 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004548 }
4549 break; // (X == 13 | X == 15) -> no change
4550 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4551 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4552 break;
4553 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4554 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4555 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4556 return ReplaceInstUsesWith(I, RHS);
4557 }
4558 break;
4559 case ICmpInst::ICMP_NE:
4560 switch (RHSCC) {
4561 default: assert(0 && "Unknown integer condition code!");
4562 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4563 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4564 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4565 return ReplaceInstUsesWith(I, LHS);
4566 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4567 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4568 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004569 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004570 }
4571 break;
4572 case ICmpInst::ICMP_ULT:
4573 switch (RHSCC) {
4574 default: assert(0 && "Unknown integer condition code!");
4575 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4576 break;
4577 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4578 // If RHSCst is [us]MAXINT, it is always false. Not handling
4579 // this can cause overflow.
4580 if (RHSCst->isMaxValue(false))
4581 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004582 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4583 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4585 break;
4586 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4587 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4588 return ReplaceInstUsesWith(I, RHS);
4589 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4590 break;
4591 }
4592 break;
4593 case ICmpInst::ICMP_SLT:
4594 switch (RHSCC) {
4595 default: assert(0 && "Unknown integer condition code!");
4596 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4597 break;
4598 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4599 // If RHSCst is [us]MAXINT, it is always false. Not handling
4600 // this can cause overflow.
4601 if (RHSCst->isMaxValue(true))
4602 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004603 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4604 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4606 break;
4607 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4608 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4609 return ReplaceInstUsesWith(I, RHS);
4610 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4611 break;
4612 }
4613 break;
4614 case ICmpInst::ICMP_UGT:
4615 switch (RHSCC) {
4616 default: assert(0 && "Unknown integer condition code!");
4617 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4618 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4619 return ReplaceInstUsesWith(I, LHS);
4620 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4621 break;
4622 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4623 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004624 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4626 break;
4627 }
4628 break;
4629 case ICmpInst::ICMP_SGT:
4630 switch (RHSCC) {
4631 default: assert(0 && "Unknown integer condition code!");
4632 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4633 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4634 return ReplaceInstUsesWith(I, LHS);
4635 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4636 break;
4637 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4638 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004639 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4641 break;
4642 }
4643 break;
4644 }
4645 return 0;
4646}
4647
Bill Wendlinga698a472008-12-01 08:23:25 +00004648/// FoldOrWithConstants - This helper function folds:
4649///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004650/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004651///
4652/// into:
4653///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004654/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004655///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004656/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004657Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004658 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004659 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4660 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004661
Bill Wendling286a0542008-12-02 06:24:20 +00004662 Value *V1 = 0;
4663 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004664 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004665
Bill Wendling29976b92008-12-02 06:18:11 +00004666 APInt Xor = CI1->getValue() ^ CI2->getValue();
4667 if (!Xor.isAllOnesValue()) return 0;
4668
Bill Wendling286a0542008-12-02 06:24:20 +00004669 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004670 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004671 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4672 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004673 }
4674
4675 return 0;
4676}
4677
Chris Lattner7e708292002-06-25 16:13:24 +00004678Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004679 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004680 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004681
Chris Lattner42593e62007-03-24 23:56:43 +00004682 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004683 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004684
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004685 // or X, X = X
4686 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004687 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004688
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004689 // See if we can simplify any instructions used by the instruction whose sole
4690 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004691 if (SimplifyDemandedInstructionBits(I))
4692 return &I;
4693 if (isa<VectorType>(I.getType())) {
4694 if (isa<ConstantAggregateZero>(Op1)) {
4695 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4696 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4697 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4698 return ReplaceInstUsesWith(I, I.getOperand(1));
4699 }
Chris Lattner42593e62007-03-24 23:56:43 +00004700 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004701
Chris Lattner3f5b8772002-05-06 16:14:14 +00004702 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004703 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004704 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004705 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004706 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4707 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004708 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004709 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004710 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004712 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004713 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004714
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004715 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004716 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4717 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004718 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004719 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004720 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004721 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004722 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004723 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004724
4725 // Try to fold constant and into select arguments.
4726 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004727 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004728 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004729 if (isa<PHINode>(Op0))
4730 if (Instruction *NV = FoldOpIntoPhi(I))
4731 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004732 }
4733
Chris Lattner4f637d42006-01-06 17:59:59 +00004734 Value *A = 0, *B = 0;
4735 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004736
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004737 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004738 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4739 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004740 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004741 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4742 return ReplaceInstUsesWith(I, Op0);
4743
Chris Lattner6423d4c2006-07-10 20:25:24 +00004744 // (A | B) | C and A | (B | C) -> bswap if possible.
4745 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004746 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4747 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4748 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4749 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004750 if (Instruction *BSwap = MatchBSwap(I))
4751 return BSwap;
4752 }
4753
Chris Lattner6e4c6492005-05-09 04:58:36 +00004754 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004755 if (Op0->hasOneUse() &&
4756 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004757 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004758 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004759 InsertNewInstBefore(NOr, I);
4760 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004761 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004762 }
4763
4764 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004765 if (Op1->hasOneUse() &&
4766 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004767 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004768 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004769 InsertNewInstBefore(NOr, I);
4770 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004771 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004772 }
4773
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004774 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004775 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004776 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4777 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004778 Value *V1 = 0, *V2 = 0, *V3 = 0;
4779 C1 = dyn_cast<ConstantInt>(C);
4780 C2 = dyn_cast<ConstantInt>(D);
4781 if (C1 && C2) { // (A & C1)|(B & C2)
4782 // If we have: ((V + N) & C1) | (V & C2)
4783 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4784 // replace with V+N.
4785 if (C1->getValue() == ~C2->getValue()) {
4786 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004787 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004788 // Add commutes, try both ways.
4789 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4790 return ReplaceInstUsesWith(I, A);
4791 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4792 return ReplaceInstUsesWith(I, A);
4793 }
4794 // Or commutes, try both ways.
4795 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004796 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004797 // Add commutes, try both ways.
4798 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4799 return ReplaceInstUsesWith(I, B);
4800 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4801 return ReplaceInstUsesWith(I, B);
4802 }
4803 }
Chris Lattner044e5332007-04-08 08:01:49 +00004804 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004805 }
4806
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004807 // Check to see if we have any common things being and'ed. If so, find the
4808 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004809 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4810 if (A == B) // (A & C)|(A & D) == A & (C|D)
4811 V1 = A, V2 = C, V3 = D;
4812 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4813 V1 = A, V2 = B, V3 = C;
4814 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4815 V1 = C, V2 = A, V3 = D;
4816 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4817 V1 = C, V2 = A, V3 = B;
4818
4819 if (V1) {
4820 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004821 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4822 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004823 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004824 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004825
Dan Gohman1975d032008-10-30 20:40:10 +00004826 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004827 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004828 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004829 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004830 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004831 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004832 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004833 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004834 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004835
Bill Wendlingb01865c2008-11-30 13:52:49 +00004836 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004837 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4838 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004839 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004840 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4842 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004843 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4846 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004849 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4850 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004852 }
Chris Lattnere511b742006-11-14 07:46:50 +00004853
4854 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004855 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4856 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4857 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004858 SI0->getOperand(1) == SI1->getOperand(1) &&
4859 (SI0->hasOneUse() || SI1->hasOneUse())) {
4860 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004861 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004862 SI1->getOperand(0),
4863 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004864 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004865 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004866 }
4867 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004868
Bill Wendlingb3833d12008-12-01 01:07:11 +00004869 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004870 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004872 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004873 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004874 }
4875 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004876 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4877 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004878 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004879 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004880 }
4881
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004882 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004883 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004884 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004885 } else {
4886 A = 0;
4887 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004888 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004889 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004890 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004891 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004892
Misha Brukmancb6267b2004-07-30 12:50:08 +00004893 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004894 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004895 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004896 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004897 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004898 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004899 }
Chris Lattnera2881962003-02-18 19:28:33 +00004900
Reid Spencere4d87aa2006-12-23 06:05:41 +00004901 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4902 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004903 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004904 return R;
4905
Chris Lattner69d4ced2008-11-16 05:20:07 +00004906 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4907 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4908 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004909 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004910
4911 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004912 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004913 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004914 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004915 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4916 !isa<ICmpInst>(Op1C->getOperand(0))) {
4917 const Type *SrcTy = Op0C->getOperand(0)->getType();
4918 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4919 // Only do this if the casts both really cause code to be
4920 // generated.
4921 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4922 I.getType(), TD) &&
4923 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4924 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004925 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004926 Op1C->getOperand(0),
4927 I.getName());
4928 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004930 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004931 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004932 }
Chris Lattner99c65742007-10-24 05:38:08 +00004933 }
4934
4935
4936 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4937 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4939 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004940 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004941 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944 // If either of the constants are nans, then the whole thing returns
4945 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004947 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004948
4949 // Otherwise, no need to compare the two constants, compare the
4950 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004951 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4952 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004953 }
Evan Cheng40300622008-10-14 18:44:08 +00004954 } else {
4955 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4956 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004957 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4958 m_Value(Op0RHS)), *Context) &&
4959 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4960 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004961 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4962 // Swap RHS operands to match LHS.
4963 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4964 std::swap(Op1LHS, Op1RHS);
4965 }
4966 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4967 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4968 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004969 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4970 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004971 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4972 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004973 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004974 else if (Op0CC == FCmpInst::FCMP_FALSE)
4975 return ReplaceInstUsesWith(I, Op1);
4976 else if (Op1CC == FCmpInst::FCMP_FALSE)
4977 return ReplaceInstUsesWith(I, Op0);
4978 bool Op0Ordered;
4979 bool Op1Ordered;
4980 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4981 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4982 if (Op0Ordered == Op1Ordered) {
4983 // If both are ordered or unordered, return a new fcmp with
4984 // or'ed predicates.
4985 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004986 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004987 if (Instruction *I = dyn_cast<Instruction>(RV))
4988 return I;
4989 // Otherwise, it's a constant boolean value...
4990 return ReplaceInstUsesWith(I, RV);
4991 }
4992 }
4993 }
4994 }
Chris Lattner99c65742007-10-24 05:38:08 +00004995 }
4996 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004997
Chris Lattner7e708292002-06-25 16:13:24 +00004998 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004999}
5000
Dan Gohman844731a2008-05-13 00:00:25 +00005001namespace {
5002
Chris Lattnerc317d392004-02-16 01:20:27 +00005003// XorSelf - Implements: X ^ X --> 0
5004struct XorSelf {
5005 Value *RHS;
5006 XorSelf(Value *rhs) : RHS(rhs) {}
5007 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5008 Instruction *apply(BinaryOperator &Xor) const {
5009 return &Xor;
5010 }
5011};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005012
Dan Gohman844731a2008-05-13 00:00:25 +00005013}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005014
Chris Lattner7e708292002-06-25 16:13:24 +00005015Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005016 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005018
Evan Chengd34af782008-03-25 20:07:13 +00005019 if (isa<UndefValue>(Op1)) {
5020 if (isa<UndefValue>(Op0))
5021 // Handle undef ^ undef -> 0 special case. This is a common
5022 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005023 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005024 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005025 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005026
Chris Lattnerc317d392004-02-16 01:20:27 +00005027 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005028 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005029 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005030 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005031 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005032
5033 // See if we can simplify any instructions used by the instruction whose sole
5034 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005035 if (SimplifyDemandedInstructionBits(I))
5036 return &I;
5037 if (isa<VectorType>(I.getType()))
5038 if (isa<ConstantAggregateZero>(Op1))
5039 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005040
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005041 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005042 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005043 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5044 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5045 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5046 if (Op0I->getOpcode() == Instruction::And ||
5047 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005048 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5049 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005050 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005051 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005052 Op0I->getOperand(1)->getName()+".not");
5053 InsertNewInstBefore(NotY, I);
5054 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005055 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005056 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 }
5059 }
5060 }
5061 }
5062
5063
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005064 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005065 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005066 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005067 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005068 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005069 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005070
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005071 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005072 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005073 FCI->getOperand(0), FCI->getOperand(1));
5074 }
5075
Nick Lewycky517e1f52008-05-31 19:01:33 +00005076 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5077 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5078 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5079 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5080 Instruction::CastOps Opcode = Op0C->getOpcode();
5081 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005082 if (RHS == Context->getConstantExprCast(Opcode,
5083 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005084 Op0C->getDestTy())) {
5085 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005086 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005087 CI->getOpcode(), CI->getInversePredicate(),
5088 CI->getOperand(0), CI->getOperand(1)), I);
5089 NewCI->takeName(CI);
5090 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5091 }
5092 }
5093 }
5094 }
5095 }
5096
Reid Spencere4d87aa2006-12-23 06:05:41 +00005097 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005098 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005099 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5100 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005101 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5102 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5103 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005105 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005106
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005107 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005108 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005109 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005110 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005111 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005113 Context->getConstantExprSub(NegOp0CI,
5114 Context->getConstantInt(I.getType(), 1)),
5115 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005116 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005117 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005118 Constant *C =
5119 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005121
Chris Lattner7c4049c2004-01-12 19:35:11 +00005122 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005123 } else if (Op0I->getOpcode() == Instruction::Or) {
5124 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005125 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005126 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005127 // Anything in both C1 and C2 is known to be zero, remove it from
5128 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005129 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5130 NewRHS = Context->getConstantExprAnd(NewRHS,
5131 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005132 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005133 I.setOperand(0, Op0I->getOperand(0));
5134 I.setOperand(1, NewRHS);
5135 return &I;
5136 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005137 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005138 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005139 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005140
5141 // Try to fold constant and into select arguments.
5142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005144 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005145 if (isa<PHINode>(Op0))
5146 if (Instruction *NV = FoldOpIntoPhi(I))
5147 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005148 }
5149
Owen Andersond672ecb2009-07-03 00:17:18 +00005150 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005151 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005152 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005153
Owen Andersond672ecb2009-07-03 00:17:18 +00005154 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005155 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005156 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005157
Chris Lattner318bf792007-03-18 22:51:34 +00005158
5159 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5160 if (Op1I) {
5161 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005162 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005163 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005164 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005165 I.swapOperands();
5166 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005167 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005168 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005169 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005170 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005171 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005172 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005173 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005174 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5176 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005177 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005178 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005179 std::swap(A, B);
5180 }
Chris Lattner318bf792007-03-18 22:51:34 +00005181 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005182 I.swapOperands(); // Simplified below.
5183 std::swap(Op0, Op1);
5184 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005185 }
Chris Lattner318bf792007-03-18 22:51:34 +00005186 }
5187
5188 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5189 if (Op0I) {
5190 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005191 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5192 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005193 if (A == Op1) // (B|A)^B == (A|B)^B
5194 std::swap(A, B);
5195 if (B == Op1) { // (A|B)^B == A & ~B
5196 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005197 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5198 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005199 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005200 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005201 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005202 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005203 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005204 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5205 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005206 if (A == Op1) // (A&B)^A -> (B&A)^A
5207 std::swap(A, B);
5208 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005209 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005210 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005211 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5212 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005213 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005214 }
Chris Lattner318bf792007-03-18 22:51:34 +00005215 }
5216
5217 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5218 if (Op0I && Op1I && Op0I->isShift() &&
5219 Op0I->getOpcode() == Op1I->getOpcode() &&
5220 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5221 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5222 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005224 Op1I->getOperand(0),
5225 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005226 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005227 Op1I->getOperand(1));
5228 }
5229
5230 if (Op0I && Op1I) {
5231 Value *A, *B, *C, *D;
5232 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005233 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5234 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005235 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005236 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005237 }
5238 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005239 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5240 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005241 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005242 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005243 }
5244
5245 // (A & B)^(C & D)
5246 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005247 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5248 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005249 // (X & Y)^(X & Y) -> (Y^Z) & X
5250 Value *X = 0, *Y = 0, *Z = 0;
5251 if (A == C)
5252 X = A, Y = B, Z = D;
5253 else if (A == D)
5254 X = A, Y = B, Z = C;
5255 else if (B == C)
5256 X = B, Y = A, Z = D;
5257 else if (B == D)
5258 X = B, Y = A, Z = C;
5259
5260 if (X) {
5261 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005262 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5263 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005264 }
5265 }
5266 }
5267
Reid Spencere4d87aa2006-12-23 06:05:41 +00005268 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5269 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005270 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005271 return R;
5272
Chris Lattner6fc205f2006-05-05 06:39:07 +00005273 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005274 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005275 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005276 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5277 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005278 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005279 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5281 I.getType(), TD) &&
5282 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5283 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005284 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005285 Op1C->getOperand(0),
5286 I.getName());
5287 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005288 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005289 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005290 }
Chris Lattner99c65742007-10-24 05:38:08 +00005291 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005292
Chris Lattner7e708292002-06-25 16:13:24 +00005293 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005294}
5295
Owen Andersond672ecb2009-07-03 00:17:18 +00005296static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005297 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005298 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005299}
Chris Lattnera96879a2004-09-29 17:40:11 +00005300
Dan Gohman6de29f82009-06-15 22:12:54 +00005301static bool HasAddOverflow(ConstantInt *Result,
5302 ConstantInt *In1, ConstantInt *In2,
5303 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005304 if (IsSigned)
5305 if (In2->getValue().isNegative())
5306 return Result->getValue().sgt(In1->getValue());
5307 else
5308 return Result->getValue().slt(In1->getValue());
5309 else
5310 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005311}
5312
Dan Gohman6de29f82009-06-15 22:12:54 +00005313/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005314/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005315static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005316 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005317 bool IsSigned = false) {
5318 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005319
Dan Gohman6de29f82009-06-15 22:12:54 +00005320 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5321 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005322 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5323 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5324 ExtractElement(In1, Idx, Context),
5325 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005326 IsSigned))
5327 return true;
5328 }
5329 return false;
5330 }
5331
5332 return HasAddOverflow(cast<ConstantInt>(Result),
5333 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5334 IsSigned);
5335}
5336
5337static bool HasSubOverflow(ConstantInt *Result,
5338 ConstantInt *In1, ConstantInt *In2,
5339 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005340 if (IsSigned)
5341 if (In2->getValue().isNegative())
5342 return Result->getValue().slt(In1->getValue());
5343 else
5344 return Result->getValue().sgt(In1->getValue());
5345 else
5346 return Result->getValue().ugt(In1->getValue());
5347}
5348
Dan Gohman6de29f82009-06-15 22:12:54 +00005349/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5350/// overflowed for this type.
5351static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005352 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005353 bool IsSigned = false) {
5354 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005355
5356 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5357 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005358 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5359 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5360 ExtractElement(In1, Idx, Context),
5361 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005362 IsSigned))
5363 return true;
5364 }
5365 return false;
5366 }
5367
5368 return HasSubOverflow(cast<ConstantInt>(Result),
5369 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5370 IsSigned);
5371}
5372
Chris Lattner574da9b2005-01-13 20:14:25 +00005373/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5374/// code necessary to compute the offset from the base pointer (without adding
5375/// in the base pointer). Return the result as a signed integer of intptr size.
5376static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5377 TargetData &TD = IC.getTargetData();
5378 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005379 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005380 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005381 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005382
5383 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005384 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005385 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005386
Gabor Greif177dd3f2008-06-12 21:37:33 +00005387 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5388 ++i, ++GTI) {
5389 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005390 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005391 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5392 if (OpC->isZero()) continue;
5393
5394 // Handle a struct index, which adds its field offset to the pointer.
5395 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5396 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5397
5398 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005399 Result =
5400 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005401 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005402 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005403 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005404 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005405 GEP->getName()+".offs"), I);
5406 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005407 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005408
Owen Andersond672ecb2009-07-03 00:17:18 +00005409 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5410 Constant *OC =
5411 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005414 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 else {
5416 // Emit an add instruction.
5417 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005418 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005420 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005422 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 // Convert to correct type.
5424 if (Op->getType() != IntPtrTy) {
5425 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005426 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005428 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429 true,
5430 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 }
5432 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005433 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005435 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005437 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 GEP->getName()+".idx"), I);
5439 }
5440
5441 // Emit an add instruction.
5442 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005443 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 cast<Constant>(Result));
5445 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005446 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005448 }
5449 return Result;
5450}
5451
Chris Lattner10c0d912008-04-22 02:53:33 +00005452
5453/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5454/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5455/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5456/// complex, and scales are involved. The above expression would also be legal
5457/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5458/// later form is less amenable to optimization though, and we are allowed to
5459/// generate the first by knowing that pointer arithmetic doesn't overflow.
5460///
5461/// If we can't emit an optimized form for this expression, this returns null.
5462///
5463static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005465 TargetData &TD = IC.getTargetData();
5466 gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468 // Check to see if this gep only has a single variable index. If so, and if
5469 // any constant indices are a multiple of its scale, then we can compute this
5470 // in terms of the scale of the variable index. For example, if the GEP
5471 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472 // because the expression will cross zero at the same point.
5473 unsigned i, e = GEP->getNumOperands();
5474 int64_t Offset = 0;
5475 for (i = 1; i != e; ++i, ++GTI) {
5476 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477 // Compute the aggregate offset of constant indices.
5478 if (CI->isZero()) continue;
5479
5480 // Handle a struct index, which adds its field offset to the pointer.
5481 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005484 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005485 Offset += Size*CI->getSExtValue();
5486 }
5487 } else {
5488 // Found our variable index.
5489 break;
5490 }
5491 }
5492
5493 // If there are no variable indices, we must have a constant offset, just
5494 // evaluate it the general way.
5495 if (i == e) return 0;
5496
5497 Value *VariableIdx = GEP->getOperand(i);
5498 // Determine the scale factor of the variable element. For example, this is
5499 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005500 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005501
5502 // Verify that there are no other variable indices. If so, emit the hard way.
5503 for (++i, ++GTI; i != e; ++i, ++GTI) {
5504 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505 if (!CI) return 0;
5506
5507 // Compute the aggregate offset of constant indices.
5508 if (CI->isZero()) continue;
5509
5510 // Handle a struct index, which adds its field offset to the pointer.
5511 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005514 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005515 Offset += Size*CI->getSExtValue();
5516 }
5517 }
5518
5519 // Okay, we know we have a single variable index, which must be a
5520 // pointer/array/vector index. If there is no offset, life is simple, return
5521 // the index.
5522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523 if (Offset == 0) {
5524 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5525 // we don't need to bother extending: the extension won't affect where the
5526 // computation crosses zero.
5527 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5529 VariableIdx->getNameStart(), &I);
5530 return VariableIdx;
5531 }
5532
5533 // Otherwise, there is an index. The computation we will do will be modulo
5534 // the pointer size, so get it.
5535 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536
5537 Offset &= PtrSizeMask;
5538 VariableScale &= PtrSizeMask;
5539
5540 // To do this transformation, any constant index must be a multiple of the
5541 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5542 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5543 // multiple of the variable scale.
5544 int64_t NewOffs = Offset / (int64_t)VariableScale;
5545 if (Offset != NewOffs*(int64_t)VariableScale)
5546 return 0;
5547
5548 // Okay, we can do this evaluation. Start by converting the index to intptr.
5549 const Type *IntPtrTy = TD.getIntPtrType();
5550 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005551 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005552 true /*SExt*/,
5553 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005554 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005555 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005556}
5557
5558
Reid Spencere4d87aa2006-12-23 06:05:41 +00005559/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005560/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005561Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5562 ICmpInst::Predicate Cond,
5563 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005564 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005565
Chris Lattner10c0d912008-04-22 02:53:33 +00005566 // Look through bitcasts.
5567 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5568 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005569
Chris Lattner574da9b2005-01-13 20:14:25 +00005570 Value *PtrBase = GEPLHS->getOperand(0);
5571 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005572 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005573 // This transformation (ignoring the base and scales) is valid because we
5574 // know pointers can't overflow. See if we can output an optimized form.
5575 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5576
5577 // If not, synthesize the offset the hard way.
5578 if (Offset == 0)
5579 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005580 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005581 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005582 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005583 // If the base pointers are different, but the indices are the same, just
5584 // compare the base pointer.
5585 if (PtrBase != GEPRHS->getOperand(0)) {
5586 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005587 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005588 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005589 if (IndicesTheSame)
5590 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5592 IndicesTheSame = false;
5593 break;
5594 }
5595
5596 // If all indices are the same, just compare the base pointers.
5597 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005598 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005599 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005600
5601 // Otherwise, the base pointers are different and the indices are
5602 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005603 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005604 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005605
Chris Lattnere9d782b2005-01-13 22:25:21 +00005606 // If one of the GEPs has all zero indices, recurse.
5607 bool AllZeros = true;
5608 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5609 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5610 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5611 AllZeros = false;
5612 break;
5613 }
5614 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005615 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5616 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005617
5618 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005619 AllZeros = true;
5620 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5622 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5623 AllZeros = false;
5624 break;
5625 }
5626 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005627 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005628
Chris Lattner4401c9c2005-01-14 00:20:05 +00005629 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5630 // If the GEPs only differ by one index, compare it.
5631 unsigned NumDifferences = 0; // Keep track of # differences.
5632 unsigned DiffOperand = 0; // The operand that differs.
5633 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005635 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5636 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005637 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 NumDifferences = 2;
5639 break;
5640 } else {
5641 if (NumDifferences++) break;
5642 DiffOperand = i;
5643 }
5644 }
5645
5646 if (NumDifferences == 0) // SAME GEP?
5647 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005648 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005649 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005650
Chris Lattner4401c9c2005-01-14 00:20:05 +00005651 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005652 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5653 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005654 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005655 return new ICmpInst(*Context,
5656 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005657 }
5658 }
5659
Reid Spencere4d87aa2006-12-23 06:05:41 +00005660 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005661 // the result to fold to a constant!
5662 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5663 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5665 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005667 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005668 }
5669 }
5670 return 0;
5671}
5672
Chris Lattnera5406232008-05-19 20:18:56 +00005673/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674///
5675Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676 Instruction *LHSI,
5677 Constant *RHSC) {
5678 if (!isa<ConstantFP>(RHSC)) return 0;
5679 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680
5681 // Get the width of the mantissa. We don't want to hack on conversions that
5682 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005683 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005684 if (MantissaWidth == -1) return 0; // Unknown.
5685
5686 // Check to see that the input is converted from an integer type that is small
5687 // enough that preserves all bits. TODO: check here for "known" sign bits.
5688 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005689 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005690
5691 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005692 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005694 ++InputSize;
5695
5696 // If the conversion would lose info, don't hack on this.
5697 if ((int)InputSize > MantissaWidth)
5698 return 0;
5699
5700 // Otherwise, we can potentially simplify the comparison. We know that it
5701 // will always come through as an integer value and we know the constant is
5702 // not a NAN (it would have been previously simplified).
5703 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704
5705 ICmpInst::Predicate Pred;
5706 switch (I.getPredicate()) {
5707 default: assert(0 && "Unexpected predicate!");
5708 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 case FCmpInst::FCMP_OEQ:
5710 Pred = ICmpInst::ICMP_EQ;
5711 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OGT:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OGE:
5718 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OLT:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OLE:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_ONE:
5730 Pred = ICmpInst::ICMP_NE;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005733 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005735 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005736 }
5737
5738 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739
5740 // Now we know that the APFloat is a normal number, zero or inf.
5741
Chris Lattner85162782008-05-20 03:50:52 +00005742 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005743 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005744 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005745
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005746 if (!LHSUnsigned) {
5747 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5748 // and large values.
5749 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751 APFloat::rmNearestTiesToEven);
5752 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5754 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005755 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5756 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 }
5758 } else {
5759 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760 // +INF and large values.
5761 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763 APFloat::rmNearestTiesToEven);
5764 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5765 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5766 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005767 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5768 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 }
Chris Lattnera5406232008-05-19 20:18:56 +00005770 }
5771
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005772 if (!LHSUnsigned) {
5773 // See if the RHS value is < SignedMin.
5774 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776 APFloat::rmNearestTiesToEven);
5777 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005780 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005782 }
Chris Lattnera5406232008-05-19 20:18:56 +00005783 }
5784
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005785 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786 // [0, UMAX], but it may still be fractional. See if it is fractional by
5787 // casting the FP value to the integer value and back, checking for equality.
5788 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005789 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005790 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5791 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005792 if (!RHS.isZero()) {
5793 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005794 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5795 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005796 if (!Equal) {
5797 // If we had a comparison against a fractional value, we have to adjust
5798 // the compare predicate and sometimes the value. RHSC is rounded towards
5799 // zero at this point.
5800 switch (Pred) {
5801 default: assert(0 && "Unexpected integer comparison!");
5802 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005803 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005805 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005806 case ICmpInst::ICMP_ULE:
5807 // (float)int <= 4.4 --> int <= 4
5808 // (float)int <= -4.4 --> false
5809 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005810 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005811 break;
5812 case ICmpInst::ICMP_SLE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> int < -4
5815 if (RHS.isNegative())
5816 Pred = ICmpInst::ICMP_SLT;
5817 break;
5818 case ICmpInst::ICMP_ULT:
5819 // (float)int < -4.4 --> false
5820 // (float)int < 4.4 --> int <= 4
5821 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005822 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005823 Pred = ICmpInst::ICMP_ULE;
5824 break;
5825 case ICmpInst::ICMP_SLT:
5826 // (float)int < -4.4 --> int < -4
5827 // (float)int < 4.4 --> int <= 4
5828 if (!RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLE;
5830 break;
5831 case ICmpInst::ICMP_UGT:
5832 // (float)int > 4.4 --> int > 4
5833 // (float)int > -4.4 --> true
5834 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005835 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005836 break;
5837 case ICmpInst::ICMP_SGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> int >= -4
5840 if (RHS.isNegative())
5841 Pred = ICmpInst::ICMP_SGE;
5842 break;
5843 case ICmpInst::ICMP_UGE:
5844 // (float)int >= -4.4 --> true
5845 // (float)int >= 4.4 --> int > 4
5846 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005847 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005848 Pred = ICmpInst::ICMP_UGT;
5849 break;
5850 case ICmpInst::ICMP_SGE:
5851 // (float)int >= -4.4 --> int >= -4
5852 // (float)int >= 4.4 --> int > 4
5853 if (!RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGT;
5855 break;
5856 }
Chris Lattnera5406232008-05-19 20:18:56 +00005857 }
5858 }
5859
5860 // Lower this FP comparison into an appropriate integer version of the
5861 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005862 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005863}
5864
Reid Spencere4d87aa2006-12-23 06:05:41 +00005865Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005868
Chris Lattner58e97462007-01-14 19:42:17 +00005869 // Fold trivial predicates.
5870 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005871 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005872 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005873 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005874
5875 // Simplify 'fcmp pred X, X'
5876 if (Op0 == Op1) {
5877 switch (I.getPredicate()) {
5878 default: assert(0 && "Unknown predicate!");
5879 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5880 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5881 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005882 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005883 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5884 case FCmpInst::FCMP_OLT: // True if ordered and less than
5885 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005886 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005887
5888 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5889 case FCmpInst::FCMP_ULT: // True if unordered or less than
5890 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5891 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5892 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005894 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005895 return &I;
5896
5897 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5898 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5899 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5900 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5901 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005903 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005904 return &I;
5905 }
5906 }
5907
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005909 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005910
Reid Spencere4d87aa2006-12-23 06:05:41 +00005911 // Handle fcmp with constant RHS
5912 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005913 // If the constant is a nan, see if we can fold the comparison based on it.
5914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915 if (CFP->getValueAPF().isNaN()) {
5916 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005917 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005918 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919 "Comparison must be either ordered or unordered!");
5920 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005921 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005922 }
5923 }
5924
Reid Spencere4d87aa2006-12-23 06:05:41 +00005925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926 switch (LHSI->getOpcode()) {
5927 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005928 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929 // block. If in the same block, we're encouraging jump threading. If
5930 // not, we are just pessimizing the code by making an i1 phi.
5931 if (LHSI->getParent() == I.getParent())
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005935 case Instruction::SIToFP:
5936 case Instruction::UIToFP:
5937 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938 return NV;
5939 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 case Instruction::Select:
5941 // If either operand of the select is a constant, we can fold the
5942 // comparison into the select arms, which will cause one to be
5943 // constant folded and the select turned into a bitwise or.
5944 Value *Op1 = 0, *Op2 = 0;
5945 if (LHSI->hasOneUse()) {
5946 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005948 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005950 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005951 LHSI->getOperand(2), RHSC,
5952 I.getName()), I);
5953 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005955 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005957 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 LHSI->getOperand(1), RHSC,
5959 I.getName()), I);
5960 }
5961 }
5962
5963 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005964 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 break;
5966 }
5967 }
5968
5969 return Changed ? &I : 0;
5970}
5971
5972Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973 bool Changed = SimplifyCompare(I);
5974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975 const Type *Ty = Op0->getType();
5976
5977 // icmp X, X
5978 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005979 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005980 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981
5982 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005983 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005984
Reid Spencere4d87aa2006-12-23 06:05:41 +00005985 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005986 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005987 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988 isa<ConstantPointerNull>(Op0)) &&
5989 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005990 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005991 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005992 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005993
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005995 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 switch (I.getPredicate()) {
5997 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005999 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006000 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006001 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006002 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006003 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006005
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006008 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006010 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006011 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006012 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006013 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_SGT:
6015 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006016 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6018 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6019 InsertNewInstBefore(Not, I);
6020 return BinaryOperator::CreateAnd(Not, Op0);
6021 }
6022 case ICmpInst::ICMP_UGE:
6023 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6024 // FALL THROUGH
6025 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006026 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006027 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006029 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGE:
6031 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6034 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6035 InsertNewInstBefore(Not, I);
6036 return BinaryOperator::CreateOr(Not, Op0);
6037 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006038 }
Chris Lattner8b170942002-08-09 23:47:40 +00006039 }
6040
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 unsigned BitWidth = 0;
6042 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006043 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044 else if (Ty->isIntOrIntVector())
6045 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006046
6047 bool isSignBit = false;
6048
Dan Gohman81b28ce2008-09-16 18:46:06 +00006049 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006050 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006051 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006052
Chris Lattnerb6566012008-01-05 01:18:20 +00006053 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006055 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006056 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006057 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006058 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006059
Dan Gohman81b28ce2008-09-16 18:46:06 +00006060 // If we have an icmp le or icmp ge instruction, turn it into the
6061 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6062 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006063 switch (I.getPredicate()) {
6064 default: break;
6065 case ICmpInst::ICMP_ULE:
6066 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006067 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006068 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6069 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006070 case ICmpInst::ICMP_SLE:
6071 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006072 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006073 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6074 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006075 case ICmpInst::ICMP_UGE:
6076 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006077 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6079 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SGE:
6081 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006082 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6084 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 }
6086
Chris Lattner183661e2008-07-11 05:40:05 +00006087 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006088 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006089 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091 }
6092
6093 // See if we can fold the comparison based on range information we can get
6094 // by checking whether bits are known to be zero or one in the input.
6095 if (BitWidth != 0) {
6096 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006100 isSignBit ? APInt::getSignBit(BitWidth)
6101 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006103 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 if (SimplifyDemandedBits(I.getOperandUse(1),
6105 APInt::getAllOnesValue(BitWidth),
6106 Op1KnownZero, Op1KnownOne, 0))
6107 return &I;
6108
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006109 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006110 // in. Compute the Min, Max and RHS values based on the known bits. For the
6111 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116 Op0Min, Op0Max);
6117 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118 Op1Min, Op1Max);
6119 } else {
6120 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121 Op0Min, Op0Max);
6122 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123 Op1Min, Op1Max);
6124 }
6125
Chris Lattner183661e2008-07-11 05:40:05 +00006126 // If Min and Max are known to be the same, then SimplifyDemandedBits
6127 // figured out that the LHS is a constant. Just constant fold this now so
6128 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006130 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006131 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006133 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006134 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135
Chris Lattner183661e2008-07-11 05:40:05 +00006136 // Based on the range information we know about the LHS, see if we can
6137 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006138 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00006139 default: assert(0 && "Unknown icmp opcode!");
6140 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006142 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006143 break;
6144 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006146 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006147 break;
6148 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006150 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006152 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159
6160 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6161 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006163 Context->getConstantIntAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 }
Chris Lattner84dff672008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006168 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006170 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171
6172 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178
6179 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6180 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006182 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 }
Chris Lattner84dff672008-07-11 05:08:55 +00006184 break;
6185 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006187 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006189 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006194 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6195 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 }
Chris Lattner84dff672008-07-11 05:08:55 +00006197 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 case ICmpInst::ICMP_SGT:
6199 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006200 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006202 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203
6204 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 }
6211 break;
6212 case ICmpInst::ICMP_SGE:
6213 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006215 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006217 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 break;
6219 case ICmpInst::ICMP_SLE:
6220 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006222 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006224 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 break;
6226 case ICmpInst::ICMP_UGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006229 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006231 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_ULE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006236 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006238 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006239 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006240 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241
6242 // Turn a signed comparison into an unsigned one if both operands
6243 // are known to have the same sign.
6244 if (I.isSignedPredicate() &&
6245 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006247 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006248 }
6249
6250 // Test if the ICmpInst instruction is used exclusively by a select as
6251 // part of a minimum or maximum operation. If so, refrain from doing
6252 // any other folding. This helps out other analyses which understand
6253 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254 // and CodeGen. And in this case, at least one of the comparison
6255 // operands has at least one user besides the compare (the select),
6256 // which would often largely negate the benefit of folding anyway.
6257 if (I.hasOneUse())
6258 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261 return 0;
6262
6263 // See if we are doing a comparison between a constant and an instruction that
6264 // can be folded into the comparison.
6265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006266 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006267 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006269 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006270 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006272 }
6273
Chris Lattner01deb9d2007-04-03 17:43:25 +00006274 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006275 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006278 case Instruction::GetElementPtr:
6279 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006281 bool isAllZeros = true;
6282 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283 if (!isa<Constant>(LHSI->getOperand(i)) ||
6284 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285 isAllZeros = false;
6286 break;
6287 }
6288 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006289 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006290 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 }
6292 break;
6293
Chris Lattner6970b662005-04-23 15:31:55 +00006294 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006295 // Only fold icmp into the PHI if the phi and fcmp are in the same
6296 // block. If in the same block, we're encouraging jump threading. If
6297 // not, we are just pessimizing the code by making an i1 phi.
6298 if (LHSI->getParent() == I.getParent())
6299 if (Instruction *NV = FoldOpIntoPhi(I))
6300 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006301 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006302 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006303 // If either operand of the select is a constant, we can fold the
6304 // comparison into the select arms, which will cause one to be
6305 // constant folded and the select turned into a bitwise or.
6306 Value *Op1 = 0, *Op2 = 0;
6307 if (LHSI->hasOneUse()) {
6308 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006310 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006311 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006312 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006313 LHSI->getOperand(2), RHSC,
6314 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006315 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006317 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006318 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006319 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320 LHSI->getOperand(1), RHSC,
6321 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006322 }
6323 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006324
Chris Lattner6970b662005-04-23 15:31:55 +00006325 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006326 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006327 break;
6328 }
Chris Lattner4802d902007-04-06 18:57:34 +00006329 case Instruction::Malloc:
6330 // If we have (malloc != null), and if the malloc has a single use, we
6331 // can assume it is successful and remove the malloc.
6332 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006334 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006335 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006336 }
6337 break;
6338 }
Chris Lattner6970b662005-04-23 15:31:55 +00006339 }
6340
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006342 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006344 return NI;
6345 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006346 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006348 return NI;
6349
Reid Spencere4d87aa2006-12-23 06:05:41 +00006350 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006351 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6352 // now.
6353 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354 if (isa<PointerType>(Op0->getType()) &&
6355 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006356 // We keep moving the cast from the left operand over to the right
6357 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006358 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006359
Chris Lattner57d86372007-01-06 01:45:59 +00006360 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361 // so eliminate it as well.
6362 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006364
Chris Lattnerde90b762003-11-03 04:25:02 +00006365 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006366 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006367 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006368 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006370 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006371 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006372 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006373 }
Owen Anderson333c4002009-07-09 23:48:35 +00006374 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 }
Chris Lattner57d86372007-01-06 01:45:59 +00006376 }
6377
6378 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006379 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006380 // This comes up when you have code like
6381 // int X = A < B;
6382 // if (X) ...
6383 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006384 // with a constant or another cast from the same type.
6385 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006386 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006387 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006388 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006389
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006390 // See if it's the same type of instruction on the left and right.
6391 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006393 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006394 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006395 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006396 default: break;
6397 case Instruction::Add:
6398 case Instruction::Sub:
6399 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006400 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006401 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006402 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006403 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405 if (CI->getValue().isSignBit()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006410 Op1I->getOperand(0));
6411 }
6412
6413 if (CI->getValue().isMaxSignedValue()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
6417 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006418 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006419 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006420 }
6421 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006422 break;
6423 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006424 if (!I.isEquality())
6425 break;
6426
Nick Lewycky5d52c452008-08-21 05:56:10 +00006427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429 // Mask = -1 >> count-trailing-zeros(Cst).
6430 if (!CI->isZero() && !CI->isOne()) {
6431 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006432 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006433 APInt::getLowBitsSet(AP.getBitWidth(),
6434 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006435 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006436 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437 Mask);
6438 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439 Mask);
6440 InsertNewInstBefore(And1, I);
6441 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006442 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006443 }
6444 }
6445 break;
6446 }
6447 }
6448 }
6449 }
6450
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006451 // ~x < ~y --> y < x
6452 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006453 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6454 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006455 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006456 }
6457
Chris Lattner65b72ba2006-09-18 04:22:48 +00006458 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006459 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006460
6461 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006462 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6463 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006464 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006465
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006466 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006467 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6468 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006470 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006471 }
6472
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006473 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006474 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006475 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006476 if (match(B, m_ConstantInt(C1), *Context) &&
6477 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006478 Constant *NC =
6479 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006480 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006481 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006482 InsertNewInstBefore(Xor, I));
6483 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484
6485 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006486 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006490 }
6491 }
6492
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006493 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006495 // A == (A^B) -> B == 0
6496 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006498 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006499 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006500
6501 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006502 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006503 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006504 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006505
6506 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006507 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006508 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006509 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006510
Chris Lattner9c2328e2006-11-14 06:06:06 +00006511 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006513 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6514 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006515 Value *X = 0, *Y = 0, *Z = 0;
6516
6517 if (A == C) {
6518 X = B; Y = D; Z = A;
6519 } else if (A == D) {
6520 X = B; Y = C; Z = A;
6521 } else if (B == C) {
6522 X = A; Y = D; Z = B;
6523 } else if (B == D) {
6524 X = A; Y = C; Z = B;
6525 }
6526
6527 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006528 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006530 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006531 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006532 return &I;
6533 }
6534 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006535 }
Chris Lattner7e708292002-06-25 16:13:24 +00006536 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006537}
6538
Chris Lattner562ef782007-06-20 23:46:26 +00006539
6540/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541/// and CmpRHS are both known to be integer constants.
6542Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543 ConstantInt *DivRHS) {
6544 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545 const APInt &CmpRHSV = CmpRHS->getValue();
6546
6547 // FIXME: If the operand types don't match the type of the divide
6548 // then don't attempt this transform. The code below doesn't have the
6549 // logic to deal with a signed divide and an unsigned compare (and
6550 // vice versa). This is because (x /s C1) <s C2 produces different
6551 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552 // (x /u C1) <u C2. Simply casting the operands and result won't
6553 // work. :( The if statement below tests that condition and bails
6554 // if it finds it.
6555 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557 return 0;
6558 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006559 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006560 if (DivIsSigned && DivRHS->isAllOnesValue())
6561 return 0; // The overflow computation also screws up here
6562 if (DivRHS->isOne())
6563 return 0; // Not worth bothering, and eliminates some funny cases
6564 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006565
6566 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6568 // C2 (CI). By solving for X we can turn this into a range check
6569 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006570 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006571
6572 // Determine if the product overflows by seeing if the product is
6573 // not equal to the divide. Make sure we do the same kind of divide
6574 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006575 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6576 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006577
6578 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006579 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006580
Chris Lattner1dbfd482007-06-21 18:11:19 +00006581 // Figure out the interval that is being checked. For example, a comparison
6582 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6583 // Compute this interval based on the constants involved and the signedness of
6584 // the compare/divide. This computes a half-open interval, keeping track of
6585 // whether either value in the interval overflows. After analysis each
6586 // overflow variable is set to 0 if it's corresponding bound variable is valid
6587 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006589 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590
Chris Lattner562ef782007-06-20 23:46:26 +00006591 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006592 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006593 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 HiOverflow = LoOverflow = ProdOV;
6595 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006596 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006597 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006598 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006599 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006600 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6601 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006602 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006603 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6605 HiOverflow = LoOverflow = ProdOV;
6606 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006607 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006608 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006610 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006611 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6612 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006613 ConstantInt* DivNeg =
6614 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6615 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006616 true) ? -1 : 0;
6617 }
Chris Lattner562ef782007-06-20 23:46:26 +00006618 }
Dan Gohman76491272008-02-13 22:09:18 +00006619 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006620 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006622 LoBound = AddOne(DivRHS, Context);
6623 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6625 HiOverflow = 1; // [INTMIN+1, overflow)
6626 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6627 }
Dan Gohman76491272008-02-13 22:09:18 +00006628 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006630 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006632 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006633 LoOverflow = AddWithOverflow(LoBound, HiBound,
6634 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006635 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006636 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6637 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006638 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006639 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006640 }
6641
Chris Lattner1dbfd482007-06-21 18:11:19 +00006642 // Dividing by a negative swaps the condition. LT <-> GT
6643 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006644 }
6645
6646 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006648 default: assert(0 && "Unhandled icmp opcode!");
6649 case ICmpInst::ICMP_EQ:
6650 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006651 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006652 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006653 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006654 ICmpInst::ICMP_UGE, X, LoBound);
6655 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006656 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006657 ICmpInst::ICMP_ULT, X, HiBound);
6658 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006659 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006660 case ICmpInst::ICMP_NE:
6661 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006662 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006663 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006664 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006665 ICmpInst::ICMP_ULT, X, LoBound);
6666 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006668 ICmpInst::ICMP_UGE, X, HiBound);
6669 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006670 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006671 case ICmpInst::ICMP_ULT:
6672 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006673 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006674 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006675 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006676 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006678 case ICmpInst::ICMP_UGT:
6679 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006680 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006681 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006682 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006683 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006684 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006685 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006686 else
Owen Anderson333c4002009-07-09 23:48:35 +00006687 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006688 }
6689}
6690
6691
Chris Lattner01deb9d2007-04-03 17:43:25 +00006692/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6693///
6694Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6695 Instruction *LHSI,
6696 ConstantInt *RHS) {
6697 const APInt &RHSV = RHS->getValue();
6698
6699 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006700 case Instruction::Trunc:
6701 if (ICI.isEquality() && LHSI->hasOneUse()) {
6702 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6703 // of the high bits truncated out of x are known.
6704 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6705 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6706 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6707 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6708 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6709
6710 // If all the high bits are known, we can do this xform.
6711 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6712 // Pull in the high bits from known-ones set.
6713 APInt NewRHS(RHS->getValue());
6714 NewRHS.zext(SrcBits);
6715 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006716 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006717 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006718 }
6719 }
6720 break;
6721
Duncan Sands0091bf22007-04-04 06:42:45 +00006722 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006723 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6724 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6725 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006726 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6727 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006728 Value *CompareVal = LHSI->getOperand(0);
6729
6730 // If the sign bit of the XorCST is not set, there is no change to
6731 // the operation, just stop using the Xor.
6732 if (!XorCST->getValue().isNegative()) {
6733 ICI.setOperand(0, CompareVal);
6734 AddToWorkList(LHSI);
6735 return &ICI;
6736 }
6737
6738 // Was the old condition true if the operand is positive?
6739 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6740
6741 // If so, the new one isn't.
6742 isTrueIfPositive ^= true;
6743
6744 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006745 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006746 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006747 else
Owen Anderson333c4002009-07-09 23:48:35 +00006748 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006749 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006750 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006751
6752 if (LHSI->hasOneUse()) {
6753 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6754 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6755 const APInt &SignBit = XorCST->getValue();
6756 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6757 ? ICI.getUnsignedPredicate()
6758 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006759 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006760 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006761 }
6762
6763 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006764 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006765 const APInt &NotSignBit = XorCST->getValue();
6766 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767 ? ICI.getUnsignedPredicate()
6768 : ICI.getSignedPredicate();
6769 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006770 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006771 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006772 }
6773 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 }
6775 break;
6776 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6777 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6778 LHSI->getOperand(0)->hasOneUse()) {
6779 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6780
6781 // If the LHS is an AND of a truncating cast, we can widen the
6782 // and/compare to be the input width without changing the value
6783 // produced, eliminating a cast.
6784 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6785 // We can do this transformation if either the AND constant does not
6786 // have its sign bit set or if it is an equality comparison.
6787 // Extending a relational comparison when we're checking the sign
6788 // bit would not work.
6789 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006790 (ICI.isEquality() ||
6791 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006792 uint32_t BitWidth =
6793 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6794 APInt NewCST = AndCST->getValue();
6795 NewCST.zext(BitWidth);
6796 APInt NewCI = RHSV;
6797 NewCI.zext(BitWidth);
6798 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006799 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006800 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006802 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006803 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006804 }
6805 }
6806
6807 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6808 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6809 // happens a LOT in code produced by the C front-end, for bitfield
6810 // access.
6811 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6812 if (Shift && !Shift->isShift())
6813 Shift = 0;
6814
6815 ConstantInt *ShAmt;
6816 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6817 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6818 const Type *AndTy = AndCST->getType(); // Type of the and.
6819
6820 // We can fold this as long as we can't shift unknown bits
6821 // into the mask. This can only happen with signed shift
6822 // rights, as they sign-extend.
6823 if (ShAmt) {
6824 bool CanFold = Shift->isLogicalShift();
6825 if (!CanFold) {
6826 // To test for the bad case of the signed shr, see if any
6827 // of the bits shifted in could be tested after the mask.
6828 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6829 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6830
6831 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6832 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6833 AndCST->getValue()) == 0)
6834 CanFold = true;
6835 }
6836
6837 if (CanFold) {
6838 Constant *NewCst;
6839 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006840 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006842 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843
6844 // Check to see if we are shifting out any of the bits being
6845 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006846 if (Context->getConstantExpr(Shift->getOpcode(),
6847 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 // If we shifted bits out, the fold is not going to work out.
6849 // As a special case, check to see if this means that the
6850 // result is always true or false now.
6851 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006852 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006853 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006854 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855 } else {
6856 ICI.setOperand(1, NewCst);
6857 Constant *NewAndCST;
6858 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006859 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006861 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 LHSI->setOperand(1, NewAndCST);
6863 LHSI->setOperand(0, Shift->getOperand(0));
6864 AddToWorkList(Shift); // Shift is dead.
6865 AddUsesToWorkList(ICI);
6866 return &ICI;
6867 }
6868 }
6869 }
6870
6871 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6872 // preferable because it allows the C<<Y expression to be hoisted out
6873 // of a loop if Y is invariant and X is not.
6874 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006875 ICI.isEquality() && !Shift->isArithmeticShift() &&
6876 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 // Compute C << Y.
6878 Value *NS;
6879 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006880 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006881 Shift->getOperand(1), "tmp");
6882 } else {
6883 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006884 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006885 Shift->getOperand(1), "tmp");
6886 }
6887 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6888
6889 // Compute X & (C << Y).
6890 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006891 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006892 InsertNewInstBefore(NewAnd, ICI);
6893
6894 ICI.setOperand(0, NewAnd);
6895 return &ICI;
6896 }
6897 }
6898 break;
6899
Chris Lattnera0141b92007-07-15 20:42:37 +00006900 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6901 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6902 if (!ShAmt) break;
6903
6904 uint32_t TypeBits = RHSV.getBitWidth();
6905
6906 // Check that the shift amount is in range. If not, don't perform
6907 // undefined shifts. When the shift is visited it will be
6908 // simplified.
6909 if (ShAmt->uge(TypeBits))
6910 break;
6911
6912 if (ICI.isEquality()) {
6913 // If we are comparing against bits always shifted out, the
6914 // comparison cannot succeed.
6915 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006916 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6917 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006918 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6919 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006920 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006921 return ReplaceInstUsesWith(ICI, Cst);
6922 }
6923
6924 if (LHSI->hasOneUse()) {
6925 // Otherwise strength reduce the shift into an and.
6926 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6927 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006928 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6929 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006930
Chris Lattnera0141b92007-07-15 20:42:37 +00006931 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006932 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006933 Mask, LHSI->getName()+".mask");
6934 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006935 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006936 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006937 }
6938 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006939
6940 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6941 bool TrueIfSigned = false;
6942 if (LHSI->hasOneUse() &&
6943 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6944 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006945 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006946 (TypeBits-ShAmt->getZExtValue()-1));
6947 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006949 Mask, LHSI->getName()+".mask");
6950 Value *And = InsertNewInstBefore(AndI, ICI);
6951
Owen Anderson333c4002009-07-09 23:48:35 +00006952 return new ICmpInst(*Context,
6953 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006954 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006955 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006956 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006957 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006958
6959 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006960 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006961 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006963 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006964
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006965 // Check that the shift amount is in range. If not, don't perform
6966 // undefined shifts. When the shift is visited it will be
6967 // simplified.
6968 uint32_t TypeBits = RHSV.getBitWidth();
6969 if (ShAmt->uge(TypeBits))
6970 break;
6971
6972 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006973
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 // If we are comparing against bits always shifted out, the
6975 // comparison cannot succeed.
6976 APInt Comp = RHSV << ShAmtVal;
6977 if (LHSI->getOpcode() == Instruction::LShr)
6978 Comp = Comp.lshr(ShAmtVal);
6979 else
6980 Comp = Comp.ashr(ShAmtVal);
6981
6982 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6983 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006984 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006985 return ReplaceInstUsesWith(ICI, Cst);
6986 }
6987
6988 // Otherwise, check to see if the bits shifted out are known to be zero.
6989 // If so, we can compare against the unshifted value:
6990 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006991 if (LHSI->hasOneUse() &&
6992 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006993 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006994 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006995 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006996 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006997
Evan Chengf30752c2008-04-23 00:38:06 +00006998 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006999 // Otherwise strength reduce the shift into an and.
7000 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00007001 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007002
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007003 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007004 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007005 Mask, LHSI->getName()+".mask");
7006 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007007 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007008 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007009 }
7010 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007011 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007012
7013 case Instruction::SDiv:
7014 case Instruction::UDiv:
7015 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7016 // Fold this div into the comparison, producing a range check.
7017 // Determine, based on the divide type, what the range is being
7018 // checked. If there is an overflow on the low or high side, remember
7019 // it, otherwise compute the range [low, hi) bounding the new value.
7020 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007021 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7022 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7023 DivRHS))
7024 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007026
7027 case Instruction::Add:
7028 // Fold: icmp pred (add, X, C1), C2
7029
7030 if (!ICI.isEquality()) {
7031 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7032 if (!LHSC) break;
7033 const APInt &LHSV = LHSC->getValue();
7034
7035 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7036 .subtract(LHSV);
7037
7038 if (ICI.isSignedPredicate()) {
7039 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007040 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007041 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007042 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007043 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007044 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007045 }
7046 } else {
7047 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007048 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007049 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007050 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007051 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007052 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007053 }
7054 }
7055 }
7056 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007057 }
7058
7059 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7060 if (ICI.isEquality()) {
7061 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7062
7063 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7064 // the second operand is a constant, simplify a bit.
7065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7066 switch (BO->getOpcode()) {
7067 case Instruction::SRem:
7068 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7069 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7070 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7071 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7072 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007073 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007074 BO->getName());
7075 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007076 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007077 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 }
7079 }
7080 break;
7081 case Instruction::Add:
7082 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7083 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7084 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007085 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007086 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007087 } else if (RHSV == 0) {
7088 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7089 // efficiently invertible, or if the add has just this one use.
7090 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7091
Owen Andersond672ecb2009-07-03 00:17:18 +00007092 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007093 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007094 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007097 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 InsertNewInstBefore(Neg, ICI);
7099 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007100 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007101 }
7102 }
7103 break;
7104 case Instruction::Xor:
7105 // For the xor case, we can xor two constants together, eliminating
7106 // the explicit xor.
7107 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007108 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007109 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110
7111 // FALLTHROUGH
7112 case Instruction::Sub:
7113 // Replace (([sub|xor] A, B) != 0) with (A != B)
7114 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007115 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116 BO->getOperand(1));
7117 break;
7118
7119 case Instruction::Or:
7120 // If bits are being or'd in that are not present in the constant we
7121 // are comparing against, then the comparison could never succeed!
7122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007123 Constant *NotCI = Context->getConstantExprNot(RHS);
7124 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7125 return ReplaceInstUsesWith(ICI,
7126 Context->getConstantInt(Type::Int1Ty,
7127 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007128 }
7129 break;
7130
7131 case Instruction::And:
7132 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7133 // If bits are being compared against that are and'd out, then the
7134 // comparison can never succeed!
7135 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007136 return ReplaceInstUsesWith(ICI,
7137 Context->getConstantInt(Type::Int1Ty,
7138 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139
7140 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7141 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007142 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007143 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007144 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007145
7146 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007147 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007148 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007149 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007150 ICmpInst::Predicate pred = isICMP_NE ?
7151 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007152 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 }
7154
7155 // ((X & ~7) == 0) --> X < 8
7156 if (RHSV == 0 && isHighOnes(BOC)) {
7157 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007158 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159 ICmpInst::Predicate pred = isICMP_NE ?
7160 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007161 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007162 }
7163 }
7164 default: break;
7165 }
7166 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7167 // Handle icmp {eq|ne} <intrinsic>, intcst.
7168 if (II->getIntrinsicID() == Intrinsic::bswap) {
7169 AddToWorkList(II);
7170 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007171 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 return &ICI;
7173 }
7174 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007175 }
7176 return 0;
7177}
7178
7179/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7180/// We only handle extending casts so far.
7181///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007182Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7183 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007184 Value *LHSCIOp = LHSCI->getOperand(0);
7185 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007186 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007187 Value *RHSCIOp;
7188
Chris Lattner8c756c12007-05-05 22:41:33 +00007189 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7190 // integer type is the same size as the pointer type.
7191 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7192 getTargetData().getPointerSizeInBits() ==
7193 cast<IntegerType>(DestTy)->getBitWidth()) {
7194 Value *RHSOp = 0;
7195 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007196 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007197 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7198 RHSOp = RHSC->getOperand(0);
7199 // If the pointer types don't match, insert a bitcast.
7200 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007201 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007202 }
7203
7204 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007205 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007206 }
7207
7208 // The code below only handles extension cast instructions, so far.
7209 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007210 if (LHSCI->getOpcode() != Instruction::ZExt &&
7211 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007212 return 0;
7213
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7215 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007216
Reid Spencere4d87aa2006-12-23 06:05:41 +00007217 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007218 // Not an extension from the same type?
7219 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 if (RHSCIOp->getType() != LHSCIOp->getType())
7221 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007222
Nick Lewycky4189a532008-01-28 03:48:02 +00007223 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007224 // and the other is a zext), then we can't handle this.
7225 if (CI->getOpcode() != LHSCI->getOpcode())
7226 return 0;
7227
Nick Lewycky4189a532008-01-28 03:48:02 +00007228 // Deal with equality cases early.
7229 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007230 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007231
7232 // A signed comparison of sign extended values simplifies into a
7233 // signed comparison.
7234 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007235 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007236
7237 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007238 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007239 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007240
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241 // If we aren't dealing with a constant on the RHS, exit early
7242 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7243 if (!CI)
7244 return 0;
7245
7246 // Compute the constant that would happen if we truncated to SrcTy then
7247 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007248 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7249 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7250 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251
7252 // If the re-extended constant didn't change...
7253 if (Res2 == CI) {
7254 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7255 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007256 // %A = sext i16 %X to i32
7257 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007259 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260 // because %A may have negative value.
7261 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007262 // However, we allow this when the compare is EQ/NE, because they are
7263 // signless.
7264 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007265 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007266 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 }
7268
7269 // The re-extended constant changed so the constant cannot be represented
7270 // in the shorter type. Consequently, we cannot emit a simple comparison.
7271
7272 // First, handle some easy cases. We know the result cannot be equal at this
7273 // point so handle the ICI.isEquality() cases
7274 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007275 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007276 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007277 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278
7279 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7280 // should have been folded away previously and not enter in here.
7281 Value *Result;
7282 if (isSignedCmp) {
7283 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007284 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007285 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007287 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288 } else {
7289 // We're performing an unsigned comparison.
7290 if (isSignedExt) {
7291 // We're performing an unsigned comp with a sign extended value.
7292 // This is true if the input is >= 0. [aka >s -1]
Owen Andersond672ecb2009-07-03 00:17:18 +00007293 Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007294 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7295 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 } else {
7297 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007298 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299 }
7300 }
7301
7302 // Finally, return the value computed.
7303 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007304 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007305 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007306
7307 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7308 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7309 "ICmp should be folded!");
7310 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007311 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Chris Lattnerf2991842008-07-11 04:09:09 +00007312 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007313}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007314
Reid Spencer832254e2007-02-02 02:16:23 +00007315Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7316 return commonShiftTransforms(I);
7317}
7318
7319Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7320 return commonShiftTransforms(I);
7321}
7322
7323Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007324 if (Instruction *R = commonShiftTransforms(I))
7325 return R;
7326
7327 Value *Op0 = I.getOperand(0);
7328
7329 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7330 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7331 if (CSI->isAllOnesValue())
7332 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007333
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007334 // See if we can turn a signed shr into an unsigned shr.
7335 if (MaskedValueIsZero(Op0,
7336 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7337 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7338
7339 // Arithmetic shifting an all-sign-bit value is a no-op.
7340 unsigned NumSignBits = ComputeNumSignBits(Op0);
7341 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7342 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007343
Chris Lattner348f6652007-12-06 01:59:46 +00007344 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007345}
7346
7347Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7348 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007350
7351 // shl X, 0 == X and shr X, 0 == X
7352 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007353 if (Op1 == Context->getNullValue(Op1->getType()) ||
7354 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007355 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007356
Reid Spencere4d87aa2006-12-23 06:05:41 +00007357 if (isa<UndefValue>(Op0)) {
7358 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007359 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007360 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007361 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007362 }
7363 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007364 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7365 return ReplaceInstUsesWith(I, Op0);
7366 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007367 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007368 }
7369
Dan Gohman9004c8a2009-05-21 02:28:33 +00007370 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007371 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007372 return &I;
7373
Chris Lattner2eefe512004-04-09 19:05:30 +00007374 // Try to fold constant and into select arguments.
7375 if (isa<Constant>(Op0))
7376 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007378 return R;
7379
Reid Spencerb83eb642006-10-20 07:07:24 +00007380 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007381 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7382 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383 return 0;
7384}
7385
Reid Spencerb83eb642006-10-20 07:07:24 +00007386Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007387 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007388 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007389
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007390 // See if we can simplify any instructions used by the instruction whose sole
7391 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007392 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007393
Dan Gohmana119de82009-06-14 23:30:43 +00007394 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7395 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007397 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007398 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007399 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007400 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007401 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007402 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007403 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404 }
7405
7406 // ((X*C1) << C2) == (X * (C1 << C2))
7407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7408 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7409 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007410 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007411 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412
7413 // Try to fold constant and into select arguments.
7414 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7415 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7416 return R;
7417 if (isa<PHINode>(Op0))
7418 if (Instruction *NV = FoldOpIntoPhi(I))
7419 return NV;
7420
Chris Lattner8999dd32007-12-22 09:07:47 +00007421 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7422 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7423 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7424 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7425 // place. Don't try to do this transformation in this case. Also, we
7426 // require that the input operand is a shift-by-constant so that we have
7427 // confidence that the shifts will get folded together. We could do this
7428 // xform in more cases, but it is unlikely to be profitable.
7429 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7430 isa<ConstantInt>(TrOp->getOperand(1))) {
7431 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007432 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007433 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007434 I.getName());
7435 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7436
7437 // For logical shifts, the truncation has the effect of making the high
7438 // part of the register be zeros. Emulate this by inserting an AND to
7439 // clear the top bits as needed. This 'and' will usually be zapped by
7440 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007441 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7442 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007443 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7444
7445 // The mask we constructed says what the trunc would do if occurring
7446 // between the shifts. We want to know the effect *after* the second
7447 // shift. We know that it is a logical shift by a constant, so adjust the
7448 // mask as appropriate.
7449 if (I.getOpcode() == Instruction::Shl)
7450 MaskV <<= Op1->getZExtValue();
7451 else {
7452 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7453 MaskV = MaskV.lshr(Op1->getZExtValue());
7454 }
7455
Owen Andersond672ecb2009-07-03 00:17:18 +00007456 Instruction *And =
7457 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7458 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007459 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7460
7461 // Return the value truncated to the interesting size.
7462 return new TruncInst(And, I.getType());
7463 }
7464 }
7465
Chris Lattner4d5542c2006-01-06 07:12:35 +00007466 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007467 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7468 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7469 Value *V1, *V2;
7470 ConstantInt *CC;
7471 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007472 default: break;
7473 case Instruction::Add:
7474 case Instruction::And:
7475 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007476 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007477 // These operators commute.
7478 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007479 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007480 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7481 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007482 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007483 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007484 Op0BO->getName());
7485 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007486 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007487 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007488 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007490 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007491 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007492 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007493 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007494
Chris Lattner150f12a2005-09-18 06:30:59 +00007495 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007496 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007497 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007498 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007499 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007500 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007501 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007502 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007503 Op0BO->getOperand(0), Op1,
7504 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 InsertNewInstBefore(YS, I); // (Y << C)
7506 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007507 BinaryOperator::CreateAnd(V1,
7508 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007509 V1->getName()+".mask");
7510 InsertNewInstBefore(XM, I); // X & (CC << C)
7511
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007514 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007515
Reid Spencera07cb7d2007-02-02 14:41:37 +00007516 // FALL THROUGH.
7517 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007518 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007520 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007522 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007523 Op0BO->getOperand(1), Op1,
7524 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007525 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007526 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007528 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007530 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007531 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007532 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007533 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007534
Chris Lattner13d4ab42006-05-31 21:14:00 +00007535 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007536 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537 match(Op0BO->getOperand(0),
7538 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007539 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007540 cast<BinaryOperator>(Op0BO->getOperand(0))
7541 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007542 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007543 Op0BO->getOperand(1), Op1,
7544 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007545 InsertNewInstBefore(YS, I); // (Y << C)
7546 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007547 BinaryOperator::CreateAnd(V1,
7548 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007549 V1->getName()+".mask");
7550 InsertNewInstBefore(XM, I); // X & (CC << C)
7551
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007553 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007554
Chris Lattner11021cb2005-09-18 05:12:10 +00007555 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007556 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007557 }
7558
7559
7560 // If the operand is an bitwise operator with a constant RHS, and the
7561 // shift is the only use, we can pull it out of the shift.
7562 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7563 bool isValid = true; // Valid only for And, Or, Xor
7564 bool highBitSet = false; // Transform if high bit of constant set?
7565
7566 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007567 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007568 case Instruction::Add:
7569 isValid = isLeftShift;
7570 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007571 case Instruction::Or:
7572 case Instruction::Xor:
7573 highBitSet = false;
7574 break;
7575 case Instruction::And:
7576 highBitSet = true;
7577 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007578 }
7579
7580 // If this is a signed shift right, and the high bit is modified
7581 // by the logical operation, do not perform the transformation.
7582 // The highBitSet boolean indicates the value of the high bit of
7583 // the constant which would cause it to be modified for this
7584 // operation.
7585 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007586 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007587 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588
7589 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007590 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007591
7592 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007593 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007594 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007595 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007596
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007597 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007598 NewRHS);
7599 }
7600 }
7601 }
7602 }
7603
Chris Lattnerad0124c2006-01-06 07:52:12 +00007604 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007605 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7606 if (ShiftOp && !ShiftOp->isShift())
7607 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007608
Reid Spencerb83eb642006-10-20 07:07:24 +00007609 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007610 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007611 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7612 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7614 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7615 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616
Zhou Sheng4351c642007-04-02 08:20:41 +00007617 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618
7619 const IntegerType *Ty = cast<IntegerType>(I.getType());
7620
7621 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007622 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007623 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7624 // saturates.
7625 if (AmtSum >= TypeBits) {
7626 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007627 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007628 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7629 }
7630
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007631 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007632 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7634 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007635 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007636 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007637
Chris Lattnerb87056f2007-02-05 00:57:54 +00007638 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007639 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7641 I.getOpcode() == Instruction::LShr) {
7642 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007643 if (AmtSum >= TypeBits)
7644 AmtSum = TypeBits-1;
7645
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007647 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 InsertNewInstBefore(Shift, I);
7649
Zhou Shenge9e03f62007-03-28 15:02:20 +00007650 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007651 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007652 }
7653
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 // Okay, if we get here, one shift must be left, and the other shift must be
7655 // right. See if the amounts are equal.
7656 if (ShiftAmt1 == ShiftAmt2) {
7657 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7658 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007659 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007660 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 }
7662 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7663 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007664 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007665 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007666 }
7667 // We can simplify ((X << C) >>s C) into a trunc + sext.
7668 // NOTE: we could do this for any C, but that would make 'unusual' integer
7669 // types. For now, just stick to ones well-supported by the code
7670 // generators.
7671 const Type *SExtType = 0;
7672 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007673 case 1 :
7674 case 8 :
7675 case 16 :
7676 case 32 :
7677 case 64 :
7678 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007679 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007680 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007681 default: break;
7682 }
7683 if (SExtType) {
7684 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7685 InsertNewInstBefore(NewTrunc, I);
7686 return new SExtInst(NewTrunc, Ty);
7687 }
7688 // Otherwise, we can't handle it yet.
7689 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007690 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007691
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007692 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693 if (I.getOpcode() == Instruction::Shl) {
7694 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7695 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007696 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007697 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007698 InsertNewInstBefore(Shift, I);
7699
Reid Spencer55702aa2007-03-25 21:11:44 +00007700 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007701 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007702 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007704 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007705 if (I.getOpcode() == Instruction::LShr) {
7706 assert(ShiftOp->getOpcode() == Instruction::Shl);
7707 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007708 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007710
Reid Spencerd5e30f02007-03-26 17:18:58 +00007711 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007712 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007713 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714
7715 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7716 } else {
7717 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007718 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007720 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 if (I.getOpcode() == Instruction::Shl) {
7722 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7723 ShiftOp->getOpcode() == Instruction::AShr);
7724 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007725 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007726 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727 InsertNewInstBefore(Shift, I);
7728
Reid Spencer55702aa2007-03-25 21:11:44 +00007729 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007730 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731 }
7732
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007733 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007734 if (I.getOpcode() == Instruction::LShr) {
7735 assert(ShiftOp->getOpcode() == Instruction::Shl);
7736 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007737 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007738 InsertNewInstBefore(Shift, I);
7739
Reid Spencer68d27cf2007-03-26 23:45:51 +00007740 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007741 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007742 }
7743
7744 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007745 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007746 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007747 return 0;
7748}
7749
Chris Lattnera1be5662002-05-02 17:06:02 +00007750
Chris Lattnercfd65102005-10-29 04:36:15 +00007751/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7752/// expression. If so, decompose it, returning some value X, such that Val is
7753/// X*Scale+Offset.
7754///
7755static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007756 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007757 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007759 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007760 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007761 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007762 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7763 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7764 if (I->getOpcode() == Instruction::Shl) {
7765 // This is a value scaled by '1 << the shift amt'.
7766 Scale = 1U << RHS->getZExtValue();
7767 Offset = 0;
7768 return I->getOperand(0);
7769 } else if (I->getOpcode() == Instruction::Mul) {
7770 // This value is scaled by 'RHS'.
7771 Scale = RHS->getZExtValue();
7772 Offset = 0;
7773 return I->getOperand(0);
7774 } else if (I->getOpcode() == Instruction::Add) {
7775 // We have X+C. Check to see if we really have (X*C2)+C1,
7776 // where C1 is divisible by C2.
7777 unsigned SubScale;
7778 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007779 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7780 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007781 Offset += RHS->getZExtValue();
7782 Scale = SubScale;
7783 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007784 }
7785 }
7786 }
7787
7788 // Otherwise, we can't look past this.
7789 Scale = 1;
7790 Offset = 0;
7791 return Val;
7792}
7793
7794
Chris Lattnerb3f83972005-10-24 06:03:58 +00007795/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7796/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007797Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007798 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007799 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007800
Chris Lattnerb53c2382005-10-24 06:22:12 +00007801 // Remove any uses of AI that are dead.
7802 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007803
Chris Lattnerb53c2382005-10-24 06:22:12 +00007804 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7805 Instruction *User = cast<Instruction>(*UI++);
7806 if (isInstructionTriviallyDead(User)) {
7807 while (UI != E && *UI == User)
7808 ++UI; // If this instruction uses AI more than once, don't break UI.
7809
Chris Lattnerb53c2382005-10-24 06:22:12 +00007810 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007811 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007812 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007813 }
7814 }
7815
Chris Lattnerb3f83972005-10-24 06:03:58 +00007816 // Get the type really allocated and the type casted to.
7817 const Type *AllocElTy = AI.getAllocatedType();
7818 const Type *CastElTy = PTy->getElementType();
7819 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007820
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007821 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7822 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007823 if (CastElTyAlign < AllocElTyAlign) return 0;
7824
Chris Lattner39387a52005-10-24 06:35:18 +00007825 // If the allocation has multiple uses, only promote it if we are strictly
7826 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007827 // same, we open the door to infinite loops of various kinds. (A reference
7828 // from a dbg.declare doesn't count as a use for this purpose.)
7829 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7830 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007831
Duncan Sands777d2302009-05-09 07:06:46 +00007832 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7833 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007834 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007835
Chris Lattner455fcc82005-10-29 03:19:53 +00007836 // See if we can satisfy the modulus by pulling a scale out of the array
7837 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007838 unsigned ArraySizeScale;
7839 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007840 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007841 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7842 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007843
Chris Lattner455fcc82005-10-29 03:19:53 +00007844 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7845 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007846 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7847 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007848
Chris Lattner455fcc82005-10-29 03:19:53 +00007849 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7850 Value *Amt = 0;
7851 if (Scale == 1) {
7852 Amt = NumElements;
7853 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007854 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007855 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007856 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007857 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007858 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007859 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007860 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007861 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007862 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007863 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007864 }
7865
Jeff Cohen86796be2007-04-04 16:58:57 +00007866 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007867 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007868 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007869 Amt = InsertNewInstBefore(Tmp, AI);
7870 }
7871
Chris Lattnerb3f83972005-10-24 06:03:58 +00007872 AllocationInst *New;
7873 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007874 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007875 else
Chris Lattner6934a042007-02-11 01:23:03 +00007876 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007877 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007878 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007879
Dale Johannesena0a66372009-03-05 00:39:02 +00007880 // If the allocation has one real use plus a dbg.declare, just remove the
7881 // declare.
7882 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7883 EraseInstFromFunction(*DI);
7884 }
7885 // If the allocation has multiple real uses, insert a cast and change all
7886 // things that used it to use the new cast. This will also hack on CI, but it
7887 // will die soon.
7888 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007889 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007890 // New is the allocation instruction, pointer typed. AI is the original
7891 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7892 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007893 InsertNewInstBefore(NewCast, AI);
7894 AI.replaceAllUsesWith(NewCast);
7895 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007896 return ReplaceInstUsesWith(CI, New);
7897}
7898
Chris Lattner70074e02006-05-13 02:06:03 +00007899/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900/// and return it as type Ty without inserting any new casts and without
7901/// changing the computed value. This is used by code that tries to decide
7902/// whether promoting or shrinking integer operations to wider or smaller types
7903/// will allow us to eliminate a truncate or extend.
7904///
7905/// This is a truncation operation if Ty is smaller than V->getType(), or an
7906/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007907///
7908/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7909/// should return true if trunc(V) can be computed by computing V in the smaller
7910/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7911/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7912/// efficiently truncated.
7913///
7914/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7915/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7916/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007917bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007918 unsigned CastOpc,
7919 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007920 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007921 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007922 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007923
7924 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007925 if (!I) return false;
7926
Dan Gohman6de29f82009-06-15 22:12:54 +00007927 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007928
Chris Lattner951626b2007-08-02 06:11:14 +00007929 // If this is an extension or truncate, we can often eliminate it.
7930 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7931 // If this is a cast from the destination type, we can trivially eliminate
7932 // it, and this will remove a cast overall.
7933 if (I->getOperand(0)->getType() == Ty) {
7934 // If the first operand is itself a cast, and is eliminable, do not count
7935 // this as an eliminable cast. We would prefer to eliminate those two
7936 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007937 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007938 ++NumCastsRemoved;
7939 return true;
7940 }
7941 }
7942
7943 // We can't extend or shrink something that has multiple uses: doing so would
7944 // require duplicating the instruction in general, which isn't profitable.
7945 if (!I->hasOneUse()) return false;
7946
Evan Chengf35fd542009-01-15 17:01:23 +00007947 unsigned Opc = I->getOpcode();
7948 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007949 case Instruction::Add:
7950 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007951 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007952 case Instruction::And:
7953 case Instruction::Or:
7954 case Instruction::Xor:
7955 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007956 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007957 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007958 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007959 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960
Chris Lattner46b96052006-11-29 07:18:39 +00007961 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007962 // If we are truncating the result of this SHL, and if it's a shift of a
7963 // constant amount, we can always perform a SHL in a smaller type.
7964 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007965 uint32_t BitWidth = Ty->getScalarSizeInBits();
7966 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007967 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007968 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007969 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970 }
7971 break;
7972 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007973 // If this is a truncate of a logical shr, we can truncate it to a smaller
7974 // lshr iff we know that the bits we would otherwise be shifting in are
7975 // already zeros.
7976 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007977 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007979 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007980 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007981 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7982 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007983 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007984 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007985 }
7986 }
Chris Lattner46b96052006-11-29 07:18:39 +00007987 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007988 case Instruction::ZExt:
7989 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007990 case Instruction::Trunc:
7991 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007992 // can safely replace it. Note that replacing it does not reduce the number
7993 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007994 if (Opc == CastOpc)
7995 return true;
7996
7997 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007998 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007999 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008000 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008001 case Instruction::Select: {
8002 SelectInst *SI = cast<SelectInst>(I);
8003 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008004 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008005 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008006 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008007 }
Chris Lattner8114b712008-06-18 04:00:49 +00008008 case Instruction::PHI: {
8009 // We can change a phi if we can change all operands.
8010 PHINode *PN = cast<PHINode>(I);
8011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8012 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008013 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008014 return false;
8015 return true;
8016 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008017 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008018 // TODO: Can handle more cases here.
8019 break;
8020 }
8021
8022 return false;
8023}
8024
8025/// EvaluateInDifferentType - Given an expression that
8026/// CanEvaluateInDifferentType returns true for, actually insert the code to
8027/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008028Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008029 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008030 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008031 return Context->getConstantExprIntegerCast(C, Ty,
8032 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008033
8034 // Otherwise, it must be an instruction.
8035 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008036 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008037 unsigned Opc = I->getOpcode();
8038 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008039 case Instruction::Add:
8040 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008041 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008042 case Instruction::And:
8043 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008044 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008045 case Instruction::AShr:
8046 case Instruction::LShr:
8047 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008048 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008049 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008050 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008051 break;
8052 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008053 case Instruction::Trunc:
8054 case Instruction::ZExt:
8055 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008057 // just return the source. There's no need to insert it because it is not
8058 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008059 if (I->getOperand(0)->getType() == Ty)
8060 return I->getOperand(0);
8061
Chris Lattner8114b712008-06-18 04:00:49 +00008062 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008063 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008064 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008065 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008066 case Instruction::Select: {
8067 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8068 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8069 Res = SelectInst::Create(I->getOperand(0), True, False);
8070 break;
8071 }
Chris Lattner8114b712008-06-18 04:00:49 +00008072 case Instruction::PHI: {
8073 PHINode *OPN = cast<PHINode>(I);
8074 PHINode *NPN = PHINode::Create(Ty);
8075 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8076 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8077 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8078 }
8079 Res = NPN;
8080 break;
8081 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008082 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008083 // TODO: Can handle more cases here.
8084 assert(0 && "Unreachable!");
8085 break;
8086 }
8087
Chris Lattner8114b712008-06-18 04:00:49 +00008088 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008089 return InsertNewInstBefore(Res, *I);
8090}
8091
Reid Spencer3da59db2006-11-27 01:05:10 +00008092/// @brief Implement the transforms common to all CastInst visitors.
8093Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008094 Value *Src = CI.getOperand(0);
8095
Dan Gohman23d9d272007-05-11 21:10:54 +00008096 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008097 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008098 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008099 if (Instruction::CastOps opc =
8100 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8101 // The first cast (CSrc) is eliminable so we need to fix up or replace
8102 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008103 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008104 }
8105 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008106
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008108 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8109 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8110 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008111
8112 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008113 if (isa<PHINode>(Src))
8114 if (Instruction *NV = FoldOpIntoPhi(CI))
8115 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008116
Reid Spencer3da59db2006-11-27 01:05:10 +00008117 return 0;
8118}
8119
Chris Lattner46cd5a12009-01-09 05:44:56 +00008120/// FindElementAtOffset - Given a type and a constant offset, determine whether
8121/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008122/// the specified offset. If so, fill them into NewIndices and return the
8123/// resultant element type, otherwise return null.
8124static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8125 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008126 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008127 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008128 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008129
8130 // Start with the index over the outer type. Note that the type size
8131 // might be zero (even if the offset isn't zero) if the indexed type
8132 // is something like [0 x {int, int}]
8133 const Type *IntPtrTy = TD->getIntPtrType();
8134 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008135 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008137 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008138
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008139 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140 if (Offset < 0) {
8141 --FirstIdx;
8142 Offset += TySize;
8143 assert(Offset >= 0);
8144 }
8145 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146 }
8147
Owen Andersond672ecb2009-07-03 00:17:18 +00008148 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008149
8150 // Index into the types. If we fail, set OrigBase to null.
8151 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008152 // Indexing into tail padding between struct/array elements.
8153 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008154 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008155
Chris Lattner46cd5a12009-01-09 05:44:56 +00008156 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008158 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159 "Offset must stay within the indexed type");
8160
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008162 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163
8164 Offset -= SL->getElementOffset(Elt);
8165 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008166 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008167 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008168 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008169 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008170 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008171 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008173 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008174 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175 }
8176 }
8177
Chris Lattner3914f722009-01-24 01:00:13 +00008178 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179}
8180
Chris Lattnerd3e28342007-04-27 17:44:50 +00008181/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183 Value *Src = CI.getOperand(0);
8184
Chris Lattnerd3e28342007-04-27 17:44:50 +00008185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008186 // If casting the result of a getelementptr instruction with no offset, turn
8187 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008188 if (GEP->hasAllZeroIndices()) {
8189 // Changing the cast operand is usually not a good idea but it is safe
8190 // here because the pointer operand is being replaced with another
8191 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008192 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008193 CI.setOperand(0, GEP->getOperand(0));
8194 return &CI;
8195 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008196
8197 // If the GEP has a single use, and the base pointer is a bitcast, and the
8198 // GEP computes a constant offset, see if we can convert these three
8199 // instructions into fewer. This typically happens with unions and other
8200 // non-type-safe code.
8201 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202 if (GEP->hasAllConstantIndices()) {
8203 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008204 ConstantInt *OffsetV =
8205 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008206 int64_t Offset = OffsetV->getSExtValue();
8207
8208 // Get the base pointer input of the bitcast, and the type it points to.
8209 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210 const Type *GEPIdxTy =
8211 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008212 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008213 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008214 // If we were able to index down into an element, create the GEP
8215 // and bitcast the result. This eliminates one bitcast, potentially
8216 // two.
8217 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8218 NewIndices.begin(),
8219 NewIndices.end(), "");
8220 InsertNewInstBefore(NGEP, CI);
8221 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008222
Chris Lattner46cd5a12009-01-09 05:44:56 +00008223 if (isa<BitCastInst>(CI))
8224 return new BitCastInst(NGEP, CI.getType());
8225 assert(isa<PtrToIntInst>(CI));
8226 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008227 }
8228 }
8229 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230 }
8231
8232 return commonCastTransforms(CI);
8233}
8234
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008235/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236/// type like i42. We don't want to introduce operations on random non-legal
8237/// integer types where they don't already exist in the code. In the future,
8238/// we should consider making this based off target-data, so that 32-bit targets
8239/// won't get i64 operations etc.
8240static bool isSafeIntegerType(const Type *Ty) {
8241 switch (Ty->getPrimitiveSizeInBits()) {
8242 case 8:
8243 case 16:
8244 case 32:
8245 case 64:
8246 return true;
8247 default:
8248 return false;
8249 }
8250}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008251
Chris Lattnerc739cd62007-03-03 05:27:34 +00008252/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8253/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008254/// cases.
8255/// @brief Implement the transforms common to CastInst with integer operands
8256Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8257 if (Instruction *Result = commonCastTransforms(CI))
8258 return Result;
8259
8260 Value *Src = CI.getOperand(0);
8261 const Type *SrcTy = Src->getType();
8262 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008263 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8264 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008265
Reid Spencer3da59db2006-11-27 01:05:10 +00008266 // See if we can simplify any instructions used by the LHS whose sole
8267 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008268 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008269 return &CI;
8270
8271 // If the source isn't an instruction or has more than one use then we
8272 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008273 Instruction *SrcI = dyn_cast<Instruction>(Src);
8274 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 return 0;
8276
Chris Lattnerc739cd62007-03-03 05:27:34 +00008277 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008279 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008280 // Only do this if the dest type is a simple type, don't convert the
8281 // expression tree to something weird like i93 unless the source is also
8282 // strange.
Dan Gohman6de29f82009-06-15 22:12:54 +00008283 (isSafeIntegerType(DestTy->getScalarType()) ||
8284 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8285 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008286 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008288 // eliminates the cast, so it is always a win. If this is a zero-extension,
8289 // we need to do an AND to maintain the clear top-part of the computation,
8290 // so we require that the input have eliminated at least one cast. If this
8291 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008292 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008293 bool DoXForm = false;
8294 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008295 switch (CI.getOpcode()) {
8296 default:
8297 // All the others use floating point so we shouldn't actually
8298 // get here because of the check above.
8299 assert(0 && "Unknown cast type");
8300 case Instruction::Trunc:
8301 DoXForm = true;
8302 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008303 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008304 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008305 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008306 // If it's unnecessary to issue an AND to clear the high bits, it's
8307 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008308 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008309 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8310 if (MaskedValueIsZero(TryRes, Mask))
8311 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008312
8313 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 if (TryI->use_empty())
8315 EraseInstFromFunction(*TryI);
8316 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008317 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008318 }
Evan Chengf35fd542009-01-15 17:01:23 +00008319 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008320 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008321 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008322 // If we do not have to emit the truncate + sext pair, then it's always
8323 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008324 //
8325 // It's not safe to eliminate the trunc + sext pair if one of the
8326 // eliminated cast is a truncate. e.g.
8327 // t2 = trunc i32 t1 to i16
8328 // t3 = sext i16 t2 to i32
8329 // !=
8330 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008331 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008332 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8333 if (NumSignBits > (DestBitSize - SrcBitSize))
8334 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008335
8336 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008337 if (TryI->use_empty())
8338 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008339 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008340 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008341 }
Evan Chengf35fd542009-01-15 17:01:23 +00008342 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008343
8344 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008345 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8346 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008347 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8348 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008349 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008350 // Just replace this cast with the result.
8351 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008352
Reid Spencer3da59db2006-11-27 01:05:10 +00008353 assert(Res->getType() == DestTy);
8354 switch (CI.getOpcode()) {
8355 default: assert(0 && "Unknown cast type!");
8356 case Instruction::Trunc:
8357 case Instruction::BitCast:
8358 // Just replace this cast with the result.
8359 return ReplaceInstUsesWith(CI, Res);
8360 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008361 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362
8363 // If the high bits are already zero, just replace this cast with the
8364 // result.
8365 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8366 if (MaskedValueIsZero(Res, Mask))
8367 return ReplaceInstUsesWith(CI, Res);
8368
8369 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008370 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008371 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008372 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008373 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374 case Instruction::SExt: {
8375 // If the high bits are already filled with sign bit, just replace this
8376 // cast with the result.
8377 unsigned NumSignBits = ComputeNumSignBits(Res);
8378 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008379 return ReplaceInstUsesWith(CI, Res);
8380
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008382 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008383 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8384 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008387 }
8388 }
8389
8390 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8391 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8392
8393 switch (SrcI->getOpcode()) {
8394 case Instruction::Add:
8395 case Instruction::Mul:
8396 case Instruction::And:
8397 case Instruction::Or:
8398 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008399 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008400 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8401 // Don't insert two casts if they cannot be eliminated. We allow
8402 // two casts to be inserted if the sizes are the same. This could
8403 // only be converting signedness, which is a noop.
8404 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008405 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8406 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008407 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008408 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8409 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008410 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008411 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 }
8413 }
8414
8415 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8416 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8417 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008418 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008419 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008420 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008421 return BinaryOperator::CreateXor(New,
8422 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008423 }
8424 break;
8425 case Instruction::SDiv:
8426 case Instruction::UDiv:
8427 case Instruction::SRem:
8428 case Instruction::URem:
8429 // If we are just changing the sign, rewrite.
8430 if (DestBitSize == SrcBitSize) {
8431 // Don't insert two casts if they cannot be eliminated. We allow
8432 // two casts to be inserted if the sizes are the same. This could
8433 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008434 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8435 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008436 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8437 Op0, DestTy, *SrcI);
8438 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8439 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008440 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008441 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8442 }
8443 }
8444 break;
8445
8446 case Instruction::Shl:
8447 // Allow changing the sign of the source operand. Do not allow
8448 // changing the size of the shift, UNLESS the shift amount is a
8449 // constant. We must not change variable sized shifts to a smaller
8450 // size, because it is undefined to shift more bits out than exist
8451 // in the value.
8452 if (DestBitSize == SrcBitSize ||
8453 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008454 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8455 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008456 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8457 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008458 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008459 }
8460 break;
8461 case Instruction::AShr:
8462 // If this is a signed shr, and if all bits shifted in are about to be
8463 // truncated off, turn it into an unsigned shr to allow greater
8464 // simplifications.
8465 if (DestBitSize < SrcBitSize &&
8466 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008467 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008468 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8469 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008470 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008471 }
8472 }
8473 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008474 }
8475 return 0;
8476}
8477
Chris Lattner8a9f5712007-04-11 06:57:46 +00008478Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008479 if (Instruction *Result = commonIntCastTransforms(CI))
8480 return Result;
8481
8482 Value *Src = CI.getOperand(0);
8483 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008484 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8485 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008486
8487 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008488 if (DestBitWidth == 1 &&
8489 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008490 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008491 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008492 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008493 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008494 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008495
Chris Lattner4f9797d2009-03-24 18:15:30 +00008496 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8497 ConstantInt *ShAmtV = 0;
8498 Value *ShiftOp = 0;
8499 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008500 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008501 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8502
8503 // Get a mask for the bits shifting in.
8504 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8505 if (MaskedValueIsZero(ShiftOp, Mask)) {
8506 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008507 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008508
8509 // Okay, we can shrink this. Truncate the input, then return a new
8510 // shift.
8511 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008512 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008513 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008514 }
8515 }
8516
8517 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008518}
8519
Evan Chengb98a10e2008-03-24 00:21:34 +00008520/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8521/// in order to eliminate the icmp.
8522Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8523 bool DoXform) {
8524 // If we are just checking for a icmp eq of a single bit and zext'ing it
8525 // to an integer, then shift the bit to the appropriate place and then
8526 // cast to integer to avoid the comparison.
8527 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8528 const APInt &Op1CV = Op1C->getValue();
8529
8530 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8531 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8532 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8533 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8534 if (!DoXform) return ICI;
8535
8536 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008537 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008538 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008539 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008540 In->getName()+".lobit"),
8541 CI);
8542 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008543 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008544 false/*ZExt*/, "tmp", &CI);
8545
8546 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008547 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008548 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008549 In->getName()+".not"),
8550 CI);
8551 }
8552
8553 return ReplaceInstUsesWith(CI, In);
8554 }
8555
8556
8557
8558 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8559 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8561 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8562 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8563 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8564 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8565 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8566 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8567 // This only works for EQ and NE
8568 ICI->isEquality()) {
8569 // If Op1C some other power of two, convert:
8570 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8571 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8572 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8573 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8574
8575 APInt KnownZeroMask(~KnownZero);
8576 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8577 if (!DoXform) return ICI;
8578
8579 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8580 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8581 // (X&4) == 2 --> false
8582 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008583 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8584 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008585 return ReplaceInstUsesWith(CI, Res);
8586 }
8587
8588 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8589 Value *In = ICI->getOperand(0);
8590 if (ShiftAmt) {
8591 // Perform a logical shr by shiftamt.
8592 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008593 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008594 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008595 In->getName()+".lobit"), CI);
8596 }
8597
8598 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008599 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008600 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008601 InsertNewInstBefore(cast<Instruction>(In), CI);
8602 }
8603
8604 if (CI.getType() == In->getType())
8605 return ReplaceInstUsesWith(CI, In);
8606 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008607 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008608 }
8609 }
8610 }
8611
8612 return 0;
8613}
8614
Chris Lattner8a9f5712007-04-11 06:57:46 +00008615Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008616 // If one of the common conversion will work ..
8617 if (Instruction *Result = commonIntCastTransforms(CI))
8618 return Result;
8619
8620 Value *Src = CI.getOperand(0);
8621
Chris Lattnera84f47c2009-02-17 20:47:23 +00008622 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8623 // types and if the sizes are just right we can convert this into a logical
8624 // 'and' which will be much cheaper than the pair of casts.
8625 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8626 // Get the sizes of the types involved. We know that the intermediate type
8627 // will be smaller than A or C, but don't know the relation between A and C.
8628 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008629 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8630 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8631 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008632 // If we're actually extending zero bits, then if
8633 // SrcSize < DstSize: zext(a & mask)
8634 // SrcSize == DstSize: a & mask
8635 // SrcSize > DstSize: trunc(a) & mask
8636 if (SrcSize < DstSize) {
8637 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008638 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008639 Instruction *And =
8640 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8641 InsertNewInstBefore(And, CI);
8642 return new ZExtInst(And, CI.getType());
8643 } else if (SrcSize == DstSize) {
8644 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008645 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008646 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008647 } else if (SrcSize > DstSize) {
8648 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8649 InsertNewInstBefore(Trunc, CI);
8650 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008651 return BinaryOperator::CreateAnd(Trunc,
8652 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008653 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008654 }
8655 }
8656
Evan Chengb98a10e2008-03-24 00:21:34 +00008657 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8658 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008659
Evan Chengb98a10e2008-03-24 00:21:34 +00008660 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8661 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8662 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8663 // of the (zext icmp) will be transformed.
8664 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8665 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8666 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8667 (transformZExtICmp(LHS, CI, false) ||
8668 transformZExtICmp(RHS, CI, false))) {
8669 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8670 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008671 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008672 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008673 }
8674
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008675 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008676 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8677 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8678 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8679 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008680 if (TI0->getType() == CI.getType())
8681 return
8682 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008683 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008684 }
8685
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008686 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8687 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8688 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8690 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8691 And->getOperand(1) == C)
8692 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8693 Value *TI0 = TI->getOperand(0);
8694 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008695 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008696 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8697 InsertNewInstBefore(NewAnd, *And);
8698 return BinaryOperator::CreateXor(NewAnd, ZC);
8699 }
8700 }
8701
Reid Spencer3da59db2006-11-27 01:05:10 +00008702 return 0;
8703}
8704
Chris Lattner8a9f5712007-04-11 06:57:46 +00008705Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008706 if (Instruction *I = commonIntCastTransforms(CI))
8707 return I;
8708
Chris Lattner8a9f5712007-04-11 06:57:46 +00008709 Value *Src = CI.getOperand(0);
8710
Dan Gohman1975d032008-10-30 20:40:10 +00008711 // Canonicalize sign-extend from i1 to a select.
8712 if (Src->getType() == Type::Int1Ty)
8713 return SelectInst::Create(Src,
Owen Andersond672ecb2009-07-03 00:17:18 +00008714 Context->getConstantIntAllOnesValue(CI.getType()),
8715 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008716
8717 // See if the value being truncated is already sign extended. If so, just
8718 // eliminate the trunc/sext pair.
8719 if (getOpcode(Src) == Instruction::Trunc) {
8720 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008721 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8722 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8723 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008724 unsigned NumSignBits = ComputeNumSignBits(Op);
8725
8726 if (OpBits == DestBits) {
8727 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8728 // bits, it is already ready.
8729 if (NumSignBits > DestBits-MidBits)
8730 return ReplaceInstUsesWith(CI, Op);
8731 } else if (OpBits < DestBits) {
8732 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8733 // bits, just sext from i32.
8734 if (NumSignBits > OpBits-MidBits)
8735 return new SExtInst(Op, CI.getType(), "tmp");
8736 } else {
8737 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8738 // bits, just truncate to i32.
8739 if (NumSignBits > OpBits-MidBits)
8740 return new TruncInst(Op, CI.getType(), "tmp");
8741 }
8742 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008743
8744 // If the input is a shl/ashr pair of a same constant, then this is a sign
8745 // extension from a smaller value. If we could trust arbitrary bitwidth
8746 // integers, we could turn this into a truncate to the smaller bit and then
8747 // use a sext for the whole extension. Since we don't, look deeper and check
8748 // for a truncate. If the source and dest are the same type, eliminate the
8749 // trunc and extend and just do shifts. For example, turn:
8750 // %a = trunc i32 %i to i8
8751 // %b = shl i8 %a, 6
8752 // %c = ashr i8 %b, 6
8753 // %d = sext i8 %c to i32
8754 // into:
8755 // %a = shl i32 %i, 30
8756 // %d = ashr i32 %a, 30
8757 Value *A = 0;
8758 ConstantInt *BA = 0, *CA = 0;
8759 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008760 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008761 BA == CA && isa<TruncInst>(A)) {
8762 Value *I = cast<TruncInst>(A)->getOperand(0);
8763 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008764 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8765 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008766 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008767 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008768 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8769 CI.getName()), CI);
8770 return BinaryOperator::CreateAShr(I, ShAmtV);
8771 }
8772 }
8773
Chris Lattnerba417832007-04-11 06:12:58 +00008774 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008775}
8776
Chris Lattnerb7530652008-01-27 05:29:54 +00008777/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008779static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008780 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008781 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008782 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008783 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008785 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 return 0;
8787}
8788
8789/// LookThroughFPExtensions - If this is an fp extension instruction, look
8790/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008791static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008792 if (Instruction *I = dyn_cast<Instruction>(V))
8793 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008794 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008795
8796 // If this value is a constant, return the constant in the smallest FP type
8797 // that can accurately represent it. This allows us to turn
8798 // (float)((double)X+2.0) into x+2.0f.
8799 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8800 if (CFP->getType() == Type::PPC_FP128Ty)
8801 return V; // No constant folding of this.
8802 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008803 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 return V;
8805 if (CFP->getType() == Type::DoubleTy)
8806 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008807 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008808 return V;
8809 // Don't try to shrink to various long double types.
8810 }
8811
8812 return V;
8813}
8814
8815Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816 if (Instruction *I = commonCastTransforms(CI))
8817 return I;
8818
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008819 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008820 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008821 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008822 // many builtins (sqrt, etc).
8823 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824 if (OpI && OpI->hasOneUse()) {
8825 switch (OpI->getOpcode()) {
8826 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008827 case Instruction::FAdd:
8828 case Instruction::FSub:
8829 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008830 case Instruction::FDiv:
8831 case Instruction::FRem:
8832 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008833 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008835 if (LHSTrunc->getType() != SrcTy &&
8836 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008837 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008838 // If the source types were both smaller than the destination type of
8839 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008840 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008842 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8843 CI.getType(), CI);
8844 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8845 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008846 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008847 }
8848 }
8849 break;
8850 }
8851 }
8852 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008853}
8854
8855Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8856 return commonCastTransforms(CI);
8857}
8858
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008859Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008860 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8861 if (OpI == 0)
8862 return commonCastTransforms(FI);
8863
8864 // fptoui(uitofp(X)) --> X
8865 // fptoui(sitofp(X)) --> X
8866 // This is safe if the intermediate type has enough bits in its mantissa to
8867 // accurately represent all values of X. For example, do not do this with
8868 // i64->float->i64. This is also safe for sitofp case, because any negative
8869 // 'X' value would cause an undefined result for the fptoui.
8870 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8871 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008872 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008873 OpI->getType()->getFPMantissaWidth())
8874 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008875
8876 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008877}
8878
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008879Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008880 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8881 if (OpI == 0)
8882 return commonCastTransforms(FI);
8883
8884 // fptosi(sitofp(X)) --> X
8885 // fptosi(uitofp(X)) --> X
8886 // This is safe if the intermediate type has enough bits in its mantissa to
8887 // accurately represent all values of X. For example, do not do this with
8888 // i64->float->i64. This is also safe for sitofp case, because any negative
8889 // 'X' value would cause an undefined result for the fptoui.
8890 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8891 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008892 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008893 OpI->getType()->getFPMantissaWidth())
8894 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008895
8896 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008897}
8898
8899Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8900 return commonCastTransforms(CI);
8901}
8902
8903Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8904 return commonCastTransforms(CI);
8905}
8906
Chris Lattnera0e69692009-03-24 18:35:40 +00008907Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8908 // If the destination integer type is smaller than the intptr_t type for
8909 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8910 // trunc to be exposed to other transforms. Don't do this for extending
8911 // ptrtoint's, because we don't know if the target sign or zero extends its
8912 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008913 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008914 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8915 TD->getIntPtrType(),
8916 "tmp"), CI);
8917 return new TruncInst(P, CI.getType());
8918 }
8919
Chris Lattnerd3e28342007-04-27 17:44:50 +00008920 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008921}
8922
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008923Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008924 // If the source integer type is larger than the intptr_t type for
8925 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8926 // allows the trunc to be exposed to other transforms. Don't do this for
8927 // extending inttoptr's, because we don't know if the target sign or zero
8928 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008929 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008930 TD->getPointerSizeInBits()) {
8931 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8932 TD->getIntPtrType(),
8933 "tmp"), CI);
8934 return new IntToPtrInst(P, CI.getType());
8935 }
8936
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008937 if (Instruction *I = commonCastTransforms(CI))
8938 return I;
8939
8940 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8941 if (!DestPointee->isSized()) return 0;
8942
8943 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8944 ConstantInt *Cst;
8945 Value *X;
8946 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008947 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008948 // If the source and destination operands have the same type, see if this
8949 // is a single-index GEP.
8950 if (X->getType() == CI.getType()) {
8951 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008952 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008953
8954 // Convert the constant to intptr type.
8955 APInt Offset = Cst->getValue();
8956 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8957
8958 // If Offset is evenly divisible by Size, we can do this xform.
8959 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8960 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersond672ecb2009-07-03 00:17:18 +00008961 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008962 }
8963 }
8964 // TODO: Could handle other cases, e.g. where add is indexing into field of
8965 // struct etc.
8966 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008967 match(CI.getOperand(0), m_Add(m_Value(X),
8968 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008969 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8970 // "inttoptr+GEP" instead of "add+intptr".
8971
8972 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008973 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008974
8975 // Convert the constant to intptr type.
8976 APInt Offset = Cst->getValue();
8977 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8978
8979 // If Offset is evenly divisible by Size, we can do this xform.
8980 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8981 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8982
8983 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8984 "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008985 return GetElementPtrInst::Create(P,
8986 Context->getConstantInt(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008987 }
8988 }
8989 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008990}
8991
Chris Lattnerd3e28342007-04-27 17:44:50 +00008992Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008993 // If the operands are integer typed then apply the integer transforms,
8994 // otherwise just apply the common ones.
8995 Value *Src = CI.getOperand(0);
8996 const Type *SrcTy = Src->getType();
8997 const Type *DestTy = CI.getType();
8998
Chris Lattner42a75512007-01-15 02:27:26 +00008999 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009000 if (Instruction *Result = commonIntCastTransforms(CI))
9001 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00009002 } else if (isa<PointerType>(SrcTy)) {
9003 if (Instruction *I = commonPointerCastTransforms(CI))
9004 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009005 } else {
9006 if (Instruction *Result = commonCastTransforms(CI))
9007 return Result;
9008 }
9009
9010
9011 // Get rid of casts from one type to the same type. These are useless and can
9012 // be replaced by the operand.
9013 if (DestTy == Src->getType())
9014 return ReplaceInstUsesWith(CI, Src);
9015
Reid Spencer3da59db2006-11-27 01:05:10 +00009016 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009017 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9018 const Type *DstElTy = DstPTy->getElementType();
9019 const Type *SrcElTy = SrcPTy->getElementType();
9020
Nate Begeman83ad90a2008-03-31 00:22:16 +00009021 // If the address spaces don't match, don't eliminate the bitcast, which is
9022 // required for changing types.
9023 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9024 return 0;
9025
Chris Lattnerd3e28342007-04-27 17:44:50 +00009026 // If we are casting a malloc or alloca to a pointer to a type of the same
9027 // size, rewrite the allocation instruction to allocate the "right" type.
9028 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9029 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9030 return V;
9031
Chris Lattnerd717c182007-05-05 22:32:24 +00009032 // If the source and destination are pointers, and this cast is equivalent
9033 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009034 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009035 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009036 unsigned NumZeros = 0;
9037 while (SrcElTy != DstElTy &&
9038 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9039 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9040 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9041 ++NumZeros;
9042 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009043
Chris Lattnerd3e28342007-04-27 17:44:50 +00009044 // If we found a path from the src to dest, create the getelementptr now.
9045 if (SrcElTy == DstElTy) {
9046 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009047 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9048 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009049 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009050 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009051
Reid Spencer3da59db2006-11-27 01:05:10 +00009052 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9053 if (SVI->hasOneUse()) {
9054 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9055 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009056 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009057 cast<VectorType>(DestTy)->getNumElements() ==
9058 SVI->getType()->getNumElements() &&
9059 SVI->getType()->getNumElements() ==
9060 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009061 CastInst *Tmp;
9062 // If either of the operands is a cast from CI.getType(), then
9063 // evaluating the shuffle in the casted destination's type will allow
9064 // us to eliminate at least one cast.
9065 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9066 Tmp->getOperand(0)->getType() == DestTy) ||
9067 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9068 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009069 Value *LHS = InsertCastBefore(Instruction::BitCast,
9070 SVI->getOperand(0), DestTy, CI);
9071 Value *RHS = InsertCastBefore(Instruction::BitCast,
9072 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009073 // Return a new shuffle vector. Use the same element ID's, as we
9074 // know the vector types match #elts.
9075 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009076 }
9077 }
9078 }
9079 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009080 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009081}
9082
Chris Lattnere576b912004-04-09 23:46:01 +00009083/// GetSelectFoldableOperands - We want to turn code that looks like this:
9084/// %C = or %A, %B
9085/// %D = select %cond, %C, %A
9086/// into:
9087/// %C = select %cond, %B, 0
9088/// %D = or %A, %C
9089///
9090/// Assuming that the specified instruction is an operand to the select, return
9091/// a bitmask indicating which operands of this instruction are foldable if they
9092/// equal the other incoming value of the select.
9093///
9094static unsigned GetSelectFoldableOperands(Instruction *I) {
9095 switch (I->getOpcode()) {
9096 case Instruction::Add:
9097 case Instruction::Mul:
9098 case Instruction::And:
9099 case Instruction::Or:
9100 case Instruction::Xor:
9101 return 3; // Can fold through either operand.
9102 case Instruction::Sub: // Can only fold on the amount subtracted.
9103 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009104 case Instruction::LShr:
9105 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009106 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009107 default:
9108 return 0; // Cannot fold
9109 }
9110}
9111
9112/// GetSelectFoldableConstant - For the same transformation as the previous
9113/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009114static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009115 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009116 switch (I->getOpcode()) {
Torok Edwin7d696d82009-07-11 13:10:19 +00009117 default: LLVM_UNREACHABLE("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009118 case Instruction::Add:
9119 case Instruction::Sub:
9120 case Instruction::Or:
9121 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009122 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009123 case Instruction::LShr:
9124 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009125 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009126 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009127 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009128 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009129 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009130 }
9131}
9132
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009133/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9134/// have the same opcode and only one use each. Try to simplify this.
9135Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9136 Instruction *FI) {
9137 if (TI->getNumOperands() == 1) {
9138 // If this is a non-volatile load or a cast from the same type,
9139 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009140 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009141 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9142 return 0;
9143 } else {
9144 return 0; // unknown unary op.
9145 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009146
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009147 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009148 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9149 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009150 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009151 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009152 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009153 }
9154
Reid Spencer832254e2007-02-02 02:16:23 +00009155 // Only handle binary operators here.
9156 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009157 return 0;
9158
9159 // Figure out if the operations have any operands in common.
9160 Value *MatchOp, *OtherOpT, *OtherOpF;
9161 bool MatchIsOpZero;
9162 if (TI->getOperand(0) == FI->getOperand(0)) {
9163 MatchOp = TI->getOperand(0);
9164 OtherOpT = TI->getOperand(1);
9165 OtherOpF = FI->getOperand(1);
9166 MatchIsOpZero = true;
9167 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9168 MatchOp = TI->getOperand(1);
9169 OtherOpT = TI->getOperand(0);
9170 OtherOpF = FI->getOperand(0);
9171 MatchIsOpZero = false;
9172 } else if (!TI->isCommutative()) {
9173 return 0;
9174 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9175 MatchOp = TI->getOperand(0);
9176 OtherOpT = TI->getOperand(1);
9177 OtherOpF = FI->getOperand(0);
9178 MatchIsOpZero = true;
9179 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9180 MatchOp = TI->getOperand(1);
9181 OtherOpT = TI->getOperand(0);
9182 OtherOpF = FI->getOperand(1);
9183 MatchIsOpZero = true;
9184 } else {
9185 return 0;
9186 }
9187
9188 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009189 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9190 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009191 InsertNewInstBefore(NewSI, SI);
9192
9193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9194 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009195 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009196 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009197 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009198 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00009199 assert(0 && "Shouldn't get here");
9200 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009201}
9202
Evan Chengde621922009-03-31 20:42:45 +00009203static bool isSelect01(Constant *C1, Constant *C2) {
9204 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9205 if (!C1I)
9206 return false;
9207 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9208 if (!C2I)
9209 return false;
9210 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9211}
9212
9213/// FoldSelectIntoOp - Try fold the select into one of the operands to
9214/// facilitate further optimization.
9215Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9216 Value *FalseVal) {
9217 // See the comment above GetSelectFoldableOperands for a description of the
9218 // transformation we are doing here.
9219 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9220 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9221 !isa<Constant>(FalseVal)) {
9222 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9223 unsigned OpToFold = 0;
9224 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9225 OpToFold = 1;
9226 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9227 OpToFold = 2;
9228 }
9229
9230 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009231 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009232 Value *OOp = TVI->getOperand(2-OpToFold);
9233 // Avoid creating select between 2 constants unless it's selecting
9234 // between 0 and 1.
9235 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9236 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9237 InsertNewInstBefore(NewSel, SI);
9238 NewSel->takeName(TVI);
9239 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9240 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9241 assert(0 && "Unknown instruction!!");
9242 }
9243 }
9244 }
9245 }
9246 }
9247
9248 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9249 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9250 !isa<Constant>(TrueVal)) {
9251 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9252 unsigned OpToFold = 0;
9253 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9254 OpToFold = 1;
9255 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9256 OpToFold = 2;
9257 }
9258
9259 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009260 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009261 Value *OOp = FVI->getOperand(2-OpToFold);
9262 // Avoid creating select between 2 constants unless it's selecting
9263 // between 0 and 1.
9264 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9265 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9266 InsertNewInstBefore(NewSel, SI);
9267 NewSel->takeName(FVI);
9268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9269 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9270 assert(0 && "Unknown instruction!!");
9271 }
9272 }
9273 }
9274 }
9275 }
9276
9277 return 0;
9278}
9279
Dan Gohman81b28ce2008-09-16 18:46:06 +00009280/// visitSelectInstWithICmp - Visit a SelectInst that has an
9281/// ICmpInst as its first operand.
9282///
9283Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9284 ICmpInst *ICI) {
9285 bool Changed = false;
9286 ICmpInst::Predicate Pred = ICI->getPredicate();
9287 Value *CmpLHS = ICI->getOperand(0);
9288 Value *CmpRHS = ICI->getOperand(1);
9289 Value *TrueVal = SI.getTrueValue();
9290 Value *FalseVal = SI.getFalseValue();
9291
9292 // Check cases where the comparison is with a constant that
9293 // can be adjusted to fit the min/max idiom. We may edit ICI in
9294 // place here, so make sure the select is the only user.
9295 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009296 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009297 switch (Pred) {
9298 default: break;
9299 case ICmpInst::ICMP_ULT:
9300 case ICmpInst::ICMP_SLT: {
9301 // X < MIN ? T : F --> F
9302 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009305 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009306 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9307 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9308 Pred = ICmpInst::getSwappedPredicate(Pred);
9309 CmpRHS = AdjustedRHS;
9310 std::swap(FalseVal, TrueVal);
9311 ICI->setPredicate(Pred);
9312 ICI->setOperand(1, CmpRHS);
9313 SI.setOperand(1, TrueVal);
9314 SI.setOperand(2, FalseVal);
9315 Changed = true;
9316 }
9317 break;
9318 }
9319 case ICmpInst::ICMP_UGT:
9320 case ICmpInst::ICMP_SGT: {
9321 // X > MAX ? T : F --> F
9322 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9323 return ReplaceInstUsesWith(SI, FalseVal);
9324 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009325 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009326 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9327 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9328 Pred = ICmpInst::getSwappedPredicate(Pred);
9329 CmpRHS = AdjustedRHS;
9330 std::swap(FalseVal, TrueVal);
9331 ICI->setPredicate(Pred);
9332 ICI->setOperand(1, CmpRHS);
9333 SI.setOperand(1, TrueVal);
9334 SI.setOperand(2, FalseVal);
9335 Changed = true;
9336 }
9337 break;
9338 }
9339 }
9340
Dan Gohman1975d032008-10-30 20:40:10 +00009341 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9342 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009343 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009344 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9345 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009346 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009347 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9348 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009349 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9350
Dan Gohman1975d032008-10-30 20:40:10 +00009351 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9352 // If we are just checking for a icmp eq of a single bit and zext'ing it
9353 // to an integer, then shift the bit to the appropriate place and then
9354 // cast to integer to avoid the comparison.
9355 const APInt &Op1CV = CI->getValue();
9356
9357 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9358 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9359 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009360 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009361 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009362 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009363 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009364 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9365 In->getName()+".lobit"),
9366 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009367 if (In->getType() != SI.getType())
9368 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009369 true/*SExt*/, "tmp", ICI);
9370
9371 if (Pred == ICmpInst::ICMP_SGT)
9372 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9373 In->getName()+".not"), *ICI);
9374
9375 return ReplaceInstUsesWith(SI, In);
9376 }
9377 }
9378 }
9379
Dan Gohman81b28ce2008-09-16 18:46:06 +00009380 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9381 // Transform (X == Y) ? X : Y -> Y
9382 if (Pred == ICmpInst::ICMP_EQ)
9383 return ReplaceInstUsesWith(SI, FalseVal);
9384 // Transform (X != Y) ? X : Y -> X
9385 if (Pred == ICmpInst::ICMP_NE)
9386 return ReplaceInstUsesWith(SI, TrueVal);
9387 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9388
9389 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9390 // Transform (X == Y) ? Y : X -> X
9391 if (Pred == ICmpInst::ICMP_EQ)
9392 return ReplaceInstUsesWith(SI, FalseVal);
9393 // Transform (X != Y) ? Y : X -> Y
9394 if (Pred == ICmpInst::ICMP_NE)
9395 return ReplaceInstUsesWith(SI, TrueVal);
9396 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9397 }
9398
9399 /// NOTE: if we wanted to, this is where to detect integer ABS
9400
9401 return Changed ? &SI : 0;
9402}
9403
Chris Lattner3d69f462004-03-12 05:52:32 +00009404Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009405 Value *CondVal = SI.getCondition();
9406 Value *TrueVal = SI.getTrueValue();
9407 Value *FalseVal = SI.getFalseValue();
9408
9409 // select true, X, Y -> X
9410 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009411 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009412 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009413
9414 // select C, X, X -> X
9415 if (TrueVal == FalseVal)
9416 return ReplaceInstUsesWith(SI, TrueVal);
9417
Chris Lattnere87597f2004-10-16 18:11:37 +00009418 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9419 return ReplaceInstUsesWith(SI, FalseVal);
9420 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9421 return ReplaceInstUsesWith(SI, TrueVal);
9422 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9423 if (isa<Constant>(TrueVal))
9424 return ReplaceInstUsesWith(SI, TrueVal);
9425 else
9426 return ReplaceInstUsesWith(SI, FalseVal);
9427 }
9428
Reid Spencer4fe16d62007-01-11 18:21:29 +00009429 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009430 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009431 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009432 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009433 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009434 } else {
9435 // Change: A = select B, false, C --> A = and !B, C
9436 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009438 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009440 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009441 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009442 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009443 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009444 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009445 } else {
9446 // Change: A = select B, C, true --> A = or !B, C
9447 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009448 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009449 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009451 }
9452 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009453
9454 // select a, b, a -> a&b
9455 // select a, a, b -> a|b
9456 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009457 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009458 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009459 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009460 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009461
Chris Lattner2eefe512004-04-09 19:05:30 +00009462 // Selecting between two integer constants?
9463 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9464 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009465 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009466 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009467 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009468 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009469 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009470 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009471 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009472 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009473 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009474 }
Chris Lattner457dd822004-06-09 07:59:58 +00009475
Reid Spencere4d87aa2006-12-23 06:05:41 +00009476 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009477
Reid Spencere4d87aa2006-12-23 06:05:41 +00009478 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009479 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009480 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009481 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009482 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009483 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009484 Value *X = IC->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009485 uint32_t Bits = X->getType()->getScalarSizeInBits();
Owen Andersond672ecb2009-07-03 00:17:18 +00009486 Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009487 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009488 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009489 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009490
9491 // Then cast to the appropriate width.
9492 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009493 }
9494 }
9495
9496
9497 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009498 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009499 // non-constant value, eliminate this whole mess. This corresponds to
9500 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009501 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009502 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009503 cast<Constant>(IC->getOperand(1))->isNullValue())
9504 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9505 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009506 isa<ConstantInt>(ICA->getOperand(1)) &&
9507 (ICA->getOperand(1) == TrueValC ||
9508 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009509 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9510 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 // know whether we have a icmp_ne or icmp_eq and whether the
9512 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009513 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009514 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009515 Value *V = ICA;
9516 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009517 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009518 Instruction::Xor, V, ICA->getOperand(1)), SI);
9519 return ReplaceInstUsesWith(SI, V);
9520 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009521 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009522 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009523
9524 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009525 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9526 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009527 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009528 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9529 // This is not safe in general for floating point:
9530 // consider X== -0, Y== +0.
9531 // It becomes safe if either operand is a nonzero constant.
9532 ConstantFP *CFPt, *CFPf;
9533 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9534 !CFPt->getValueAPF().isZero()) ||
9535 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9536 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009537 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009538 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009539 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009540 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009541 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009542 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009543
Reid Spencere4d87aa2006-12-23 06:05:41 +00009544 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009545 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009546 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9547 // This is not safe in general for floating point:
9548 // consider X== -0, Y== +0.
9549 // It becomes safe if either operand is a nonzero constant.
9550 ConstantFP *CFPt, *CFPf;
9551 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9552 !CFPt->getValueAPF().isZero()) ||
9553 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9554 !CFPf->getValueAPF().isZero()))
9555 return ReplaceInstUsesWith(SI, FalseVal);
9556 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009557 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009558 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9559 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009560 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009561 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009562 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009563 }
9564
9565 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009566 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9567 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9568 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009569
Chris Lattner87875da2005-01-13 22:52:24 +00009570 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9571 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9572 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009573 Instruction *AddOp = 0, *SubOp = 0;
9574
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009575 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9576 if (TI->getOpcode() == FI->getOpcode())
9577 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9578 return IV;
9579
9580 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9581 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009582 if ((TI->getOpcode() == Instruction::Sub &&
9583 FI->getOpcode() == Instruction::Add) ||
9584 (TI->getOpcode() == Instruction::FSub &&
9585 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009586 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009587 } else if ((FI->getOpcode() == Instruction::Sub &&
9588 TI->getOpcode() == Instruction::Add) ||
9589 (FI->getOpcode() == Instruction::FSub &&
9590 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009591 AddOp = TI; SubOp = FI;
9592 }
9593
9594 if (AddOp) {
9595 Value *OtherAddOp = 0;
9596 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9597 OtherAddOp = AddOp->getOperand(1);
9598 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9599 OtherAddOp = AddOp->getOperand(0);
9600 }
9601
9602 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009603 // So at this point we know we have (Y -> OtherAddOp):
9604 // select C, (add X, Y), (sub X, Z)
9605 Value *NegVal; // Compute -Z
9606 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009607 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009608 } else {
9609 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009610 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009611 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009612
9613 Value *NewTrueOp = OtherAddOp;
9614 Value *NewFalseOp = NegVal;
9615 if (AddOp != TI)
9616 std::swap(NewTrueOp, NewFalseOp);
9617 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009618 SelectInst::Create(CondVal, NewTrueOp,
9619 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009620
9621 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009622 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009623 }
9624 }
9625 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009626
Chris Lattnere576b912004-04-09 23:46:01 +00009627 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009628 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009629 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9630 if (FoldI)
9631 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009632 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009633
9634 if (BinaryOperator::isNot(CondVal)) {
9635 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9636 SI.setOperand(1, FalseVal);
9637 SI.setOperand(2, TrueVal);
9638 return &SI;
9639 }
9640
Chris Lattner3d69f462004-03-12 05:52:32 +00009641 return 0;
9642}
9643
Dan Gohmaneee962e2008-04-10 18:43:06 +00009644/// EnforceKnownAlignment - If the specified pointer points to an object that
9645/// we control, modify the object's alignment to PrefAlign. This isn't
9646/// often possible though. If alignment is important, a more reliable approach
9647/// is to simply align all global variables and allocation instructions to
9648/// their preferred alignment from the beginning.
9649///
9650static unsigned EnforceKnownAlignment(Value *V,
9651 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009652
Dan Gohmaneee962e2008-04-10 18:43:06 +00009653 User *U = dyn_cast<User>(V);
9654 if (!U) return Align;
9655
9656 switch (getOpcode(U)) {
9657 default: break;
9658 case Instruction::BitCast:
9659 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9660 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009661 // If all indexes are zero, it is just the alignment of the base pointer.
9662 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009663 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009664 if (!isa<Constant>(*i) ||
9665 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009666 AllZeroOperands = false;
9667 break;
9668 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009669
9670 if (AllZeroOperands) {
9671 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009672 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009673 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009674 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009675 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009676 }
9677
9678 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9679 // If there is a large requested alignment and we can, bump up the alignment
9680 // of the global.
9681 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009682 if (GV->getAlignment() >= PrefAlign)
9683 Align = GV->getAlignment();
9684 else {
9685 GV->setAlignment(PrefAlign);
9686 Align = PrefAlign;
9687 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009688 }
9689 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9690 // If there is a requested alignment and if this is an alloca, round up. We
9691 // don't do this for malloc, because some systems can't respect the request.
9692 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009693 if (AI->getAlignment() >= PrefAlign)
9694 Align = AI->getAlignment();
9695 else {
9696 AI->setAlignment(PrefAlign);
9697 Align = PrefAlign;
9698 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009699 }
9700 }
9701
9702 return Align;
9703}
9704
9705/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9706/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9707/// and it is more than the alignment of the ultimate object, see if we can
9708/// increase the alignment of the ultimate object, making this check succeed.
9709unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9710 unsigned PrefAlign) {
9711 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9712 sizeof(PrefAlign) * CHAR_BIT;
9713 APInt Mask = APInt::getAllOnesValue(BitWidth);
9714 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9715 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9716 unsigned TrailZ = KnownZero.countTrailingOnes();
9717 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9718
9719 if (PrefAlign > Align)
9720 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9721
9722 // We don't need to make any adjustment.
9723 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009724}
9725
Chris Lattnerf497b022008-01-13 23:50:23 +00009726Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009727 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009728 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009729 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009730 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009731
9732 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009733 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9734 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009735 return MI;
9736 }
9737
9738 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9739 // load/store.
9740 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9741 if (MemOpLength == 0) return 0;
9742
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 // Source and destination pointer types are always "i8*" for intrinsic. See
9744 // if the size is something we can handle with a single primitive load/store.
9745 // A single load+store correctly handles overlapping memory in the memmove
9746 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009747 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009748 if (Size == 0) return MI; // Delete this mem transfer.
9749
9750 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009751 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009752
Chris Lattner37ac6082008-01-14 00:28:35 +00009753 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009754 Type *NewPtrTy =
9755 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009756
9757 // Memcpy forces the use of i8* for the source and destination. That means
9758 // that if you're using memcpy to move one double around, you'll get a cast
9759 // from double* to i8*. We'd much rather use a double load+store rather than
9760 // an i64 load+store, here because this improves the odds that the source or
9761 // dest address will be promotable. See if we can find a better type than the
9762 // integer datatype.
9763 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9764 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9765 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9766 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9767 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009768 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009769 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9770 if (STy->getNumElements() == 1)
9771 SrcETy = STy->getElementType(0);
9772 else
9773 break;
9774 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9775 if (ATy->getNumElements() == 1)
9776 SrcETy = ATy->getElementType();
9777 else
9778 break;
9779 } else
9780 break;
9781 }
9782
Dan Gohman8f8e2692008-05-23 01:52:21 +00009783 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009784 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009785 }
9786 }
9787
9788
Chris Lattnerf497b022008-01-13 23:50:23 +00009789 // If the memcpy/memmove provides better alignment info than we can
9790 // infer, use it.
9791 SrcAlign = std::max(SrcAlign, CopyAlign);
9792 DstAlign = std::max(DstAlign, CopyAlign);
9793
9794 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9795 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009796 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9797 InsertNewInstBefore(L, *MI);
9798 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9799
9800 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009801 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009802 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009803}
Chris Lattner3d69f462004-03-12 05:52:32 +00009804
Chris Lattner69ea9d22008-04-30 06:39:11 +00009805Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9806 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009807 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009808 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9809 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009810 return MI;
9811 }
9812
9813 // Extract the length and alignment and fill if they are constant.
9814 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9815 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9816 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9817 return 0;
9818 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009819 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009820
9821 // If the length is zero, this is a no-op
9822 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9823
9824 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9825 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009826 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009827
9828 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009829 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009830
9831 // Alignment 0 is identity for alignment 1 for memset, but not store.
9832 if (Alignment == 0) Alignment = 1;
9833
9834 // Extract the fill value and store.
9835 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009836 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9837 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009838
9839 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009840 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009841 return MI;
9842 }
9843
9844 return 0;
9845}
9846
9847
Chris Lattner8b0ea312006-01-13 20:11:04 +00009848/// visitCallInst - CallInst simplification. This mostly only handles folding
9849/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9850/// the heavy lifting.
9851///
Chris Lattner9fe38862003-06-19 17:00:31 +00009852Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009853 // If the caller function is nounwind, mark the call as nounwind, even if the
9854 // callee isn't.
9855 if (CI.getParent()->getParent()->doesNotThrow() &&
9856 !CI.doesNotThrow()) {
9857 CI.setDoesNotThrow();
9858 return &CI;
9859 }
9860
9861
9862
Chris Lattner8b0ea312006-01-13 20:11:04 +00009863 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9864 if (!II) return visitCallSite(&CI);
9865
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009866 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9867 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009868 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009869 bool Changed = false;
9870
9871 // memmove/cpy/set of zero bytes is a noop.
9872 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9873 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9874
Chris Lattner35b9e482004-10-12 04:52:52 +00009875 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009876 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009877 // Replace the instruction with just byte operations. We would
9878 // transform other cases to loads/stores, but we don't know if
9879 // alignment is sufficient.
9880 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009881 }
9882
Chris Lattner35b9e482004-10-12 04:52:52 +00009883 // If we have a memmove and the source operation is a constant global,
9884 // then the source and dest pointers can't alias, so we can change this
9885 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009886 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009887 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9888 if (GVSrc->isConstant()) {
9889 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009890 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9891 const Type *Tys[1];
9892 Tys[0] = CI.getOperand(3)->getType();
9893 CI.setOperand(0,
9894 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009895 Changed = true;
9896 }
Chris Lattnera935db82008-05-28 05:30:41 +00009897
9898 // memmove(x,x,size) -> noop.
9899 if (MMI->getSource() == MMI->getDest())
9900 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009901 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009902
Chris Lattner95a959d2006-03-06 20:18:44 +00009903 // If we can determine a pointer alignment that is bigger than currently
9904 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009905 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009906 if (Instruction *I = SimplifyMemTransfer(MI))
9907 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009908 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9909 if (Instruction *I = SimplifyMemSet(MSI))
9910 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009911 }
9912
Chris Lattner8b0ea312006-01-13 20:11:04 +00009913 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009914 }
9915
9916 switch (II->getIntrinsicID()) {
9917 default: break;
9918 case Intrinsic::bswap:
9919 // bswap(bswap(x)) -> x
9920 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9921 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9922 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9923 break;
9924 case Intrinsic::ppc_altivec_lvx:
9925 case Intrinsic::ppc_altivec_lvxl:
9926 case Intrinsic::x86_sse_loadu_ps:
9927 case Intrinsic::x86_sse2_loadu_pd:
9928 case Intrinsic::x86_sse2_loadu_dq:
9929 // Turn PPC lvx -> load if the pointer is known aligned.
9930 // Turn X86 loadups -> load if the pointer is known aligned.
9931 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9932 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009933 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009934 CI);
9935 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009936 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 break;
9938 case Intrinsic::ppc_altivec_stvx:
9939 case Intrinsic::ppc_altivec_stvxl:
9940 // Turn stvx -> store if the pointer is known aligned.
9941 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9942 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009943 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009944 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9945 return new StoreInst(II->getOperand(1), Ptr);
9946 }
9947 break;
9948 case Intrinsic::x86_sse_storeu_ps:
9949 case Intrinsic::x86_sse2_storeu_pd:
9950 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009951 // Turn X86 storeu -> store if the pointer is known aligned.
9952 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9953 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009954 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009955 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9956 return new StoreInst(II->getOperand(2), Ptr);
9957 }
9958 break;
9959
9960 case Intrinsic::x86_sse_cvttss2si: {
9961 // These intrinsics only demands the 0th element of its input vector. If
9962 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009963 unsigned VWidth =
9964 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9965 APInt DemandedElts(VWidth, 1);
9966 APInt UndefElts(VWidth, 0);
9967 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009968 UndefElts)) {
9969 II->setOperand(1, V);
9970 return II;
9971 }
9972 break;
9973 }
9974
9975 case Intrinsic::ppc_altivec_vperm:
9976 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9977 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9978 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009979
Chris Lattner0521e3c2008-06-18 04:33:20 +00009980 // Check that all of the elements are integer constants or undefs.
9981 bool AllEltsOk = true;
9982 for (unsigned i = 0; i != 16; ++i) {
9983 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9984 !isa<UndefValue>(Mask->getOperand(i))) {
9985 AllEltsOk = false;
9986 break;
9987 }
9988 }
9989
9990 if (AllEltsOk) {
9991 // Cast the input vectors to byte vectors.
9992 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9993 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009994 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009995
Chris Lattner0521e3c2008-06-18 04:33:20 +00009996 // Only extract each element once.
9997 Value *ExtractedElts[32];
9998 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9999
Chris Lattnere2ed0572006-04-06 19:19:17 +000010000 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010001 if (isa<UndefValue>(Mask->getOperand(i)))
10002 continue;
10003 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10004 Idx &= 31; // Match the hardware behavior.
10005
10006 if (ExtractedElts[Idx] == 0) {
10007 Instruction *Elt =
10008 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
10009 InsertNewInstBefore(Elt, CI);
10010 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010011 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010012
Chris Lattner0521e3c2008-06-18 04:33:20 +000010013 // Insert this value into the result vector.
10014 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10015 i, "tmp");
10016 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +000010017 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010018 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010019 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010020 }
10021 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010022
Chris Lattner0521e3c2008-06-18 04:33:20 +000010023 case Intrinsic::stackrestore: {
10024 // If the save is right next to the restore, remove the restore. This can
10025 // happen when variable allocas are DCE'd.
10026 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10027 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10028 BasicBlock::iterator BI = SS;
10029 if (&*++BI == II)
10030 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010031 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010032 }
10033
10034 // Scan down this block to see if there is another stack restore in the
10035 // same block without an intervening call/alloca.
10036 BasicBlock::iterator BI = II;
10037 TerminatorInst *TI = II->getParent()->getTerminator();
10038 bool CannotRemove = false;
10039 for (++BI; &*BI != TI; ++BI) {
10040 if (isa<AllocaInst>(BI)) {
10041 CannotRemove = true;
10042 break;
10043 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010044 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10045 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10046 // If there is a stackrestore below this one, remove this one.
10047 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10048 return EraseInstFromFunction(CI);
10049 // Otherwise, ignore the intrinsic.
10050 } else {
10051 // If we found a non-intrinsic call, we can't remove the stack
10052 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010053 CannotRemove = true;
10054 break;
10055 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010056 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010057 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010058
10059 // If the stack restore is in a return/unwind block and if there are no
10060 // allocas or calls between the restore and the return, nuke the restore.
10061 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10062 return EraseInstFromFunction(CI);
10063 break;
10064 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010065 }
10066
Chris Lattner8b0ea312006-01-13 20:11:04 +000010067 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010068}
10069
10070// InvokeInst simplification
10071//
10072Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010073 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010074}
10075
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010076/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10077/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010078static bool isSafeToEliminateVarargsCast(const CallSite CS,
10079 const CastInst * const CI,
10080 const TargetData * const TD,
10081 const int ix) {
10082 if (!CI->isLosslessCast())
10083 return false;
10084
10085 // The size of ByVal arguments is derived from the type, so we
10086 // can't change to a type with a different size. If the size were
10087 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010088 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010089 return true;
10090
10091 const Type* SrcTy =
10092 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10093 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10094 if (!SrcTy->isSized() || !DstTy->isSized())
10095 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010096 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010097 return false;
10098 return true;
10099}
10100
Chris Lattnera44d8a22003-10-07 22:32:43 +000010101// visitCallSite - Improvements for call and invoke instructions.
10102//
10103Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010104 bool Changed = false;
10105
10106 // If the callee is a constexpr cast of a function, attempt to move the cast
10107 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010108 if (transformConstExprCastCall(CS)) return 0;
10109
Chris Lattner6c266db2003-10-07 22:54:13 +000010110 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010111
Chris Lattner08b22ec2005-05-13 07:09:09 +000010112 if (Function *CalleeF = dyn_cast<Function>(Callee))
10113 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10114 Instruction *OldCall = CS.getInstruction();
10115 // If the call and callee calling conventions don't match, this call must
10116 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010117 new StoreInst(Context->getConstantIntTrue(),
10118 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10119 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010120 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010121 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010122 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10123 return EraseInstFromFunction(*OldCall);
10124 return 0;
10125 }
10126
Chris Lattner17be6352004-10-18 02:59:09 +000010127 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10128 // This instruction is not reachable, just remove it. We insert a store to
10129 // undef so that we know that this code is not reachable, despite the fact
10130 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010131 new StoreInst(Context->getConstantIntTrue(),
10132 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010133 CS.getInstruction());
10134
10135 if (!CS.getInstruction()->use_empty())
10136 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010137 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010138
10139 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10140 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010141 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010142 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010143 }
Chris Lattner17be6352004-10-18 02:59:09 +000010144 return EraseInstFromFunction(*CS.getInstruction());
10145 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010146
Duncan Sandscdb6d922007-09-17 10:26:40 +000010147 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10148 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10149 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10150 return transformCallThroughTrampoline(CS);
10151
Chris Lattner6c266db2003-10-07 22:54:13 +000010152 const PointerType *PTy = cast<PointerType>(Callee->getType());
10153 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10154 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010155 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010156 // See if we can optimize any arguments passed through the varargs area of
10157 // the call.
10158 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010159 E = CS.arg_end(); I != E; ++I, ++ix) {
10160 CastInst *CI = dyn_cast<CastInst>(*I);
10161 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10162 *I = CI->getOperand(0);
10163 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010164 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010165 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010166 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010167
Duncan Sandsf0c33542007-12-19 21:13:37 +000010168 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010169 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010170 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010171 Changed = true;
10172 }
10173
Chris Lattner6c266db2003-10-07 22:54:13 +000010174 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010175}
10176
Chris Lattner9fe38862003-06-19 17:00:31 +000010177// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10178// attempt to move the cast to the arguments of the call/invoke.
10179//
10180bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10181 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10182 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010183 if (CE->getOpcode() != Instruction::BitCast ||
10184 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010185 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010186 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010187 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010188 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010189
10190 // Okay, this is a cast from a function to a different type. Unless doing so
10191 // would cause a type conversion of one of our arguments, change this call to
10192 // be a direct call with arguments casted to the appropriate types.
10193 //
10194 const FunctionType *FT = Callee->getFunctionType();
10195 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010196 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010197
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010198 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010199 return false; // TODO: Handle multiple return values.
10200
Chris Lattnerf78616b2004-01-14 06:06:08 +000010201 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010202 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010203 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010204 // Conversion is ok if changing from one pointer type to another or from
10205 // a pointer to an integer of the same size.
10206 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010207 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010208 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010209
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010210 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010211 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010212 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010213 return false; // Cannot transform this return value.
10214
Chris Lattner58d74912008-03-12 17:45:29 +000010215 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010216 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010217 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010218 return false; // Attribute not compatible with transformed value.
10219 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010220
Chris Lattnerf78616b2004-01-14 06:06:08 +000010221 // If the callsite is an invoke instruction, and the return value is used by
10222 // a PHI node in a successor, we cannot change the return type of the call
10223 // because there is no place to put the cast instruction (without breaking
10224 // the critical edge). Bail out in this case.
10225 if (!Caller->use_empty())
10226 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10227 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10228 UI != E; ++UI)
10229 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10230 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010231 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010232 return false;
10233 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010234
10235 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10236 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010237
Chris Lattner9fe38862003-06-19 17:00:31 +000010238 CallSite::arg_iterator AI = CS.arg_begin();
10239 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10240 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010241 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010242
10243 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010244 return false; // Cannot transform this parameter value.
10245
Devang Patel19c87462008-09-26 22:53:05 +000010246 if (CallerPAL.getParamAttributes(i + 1)
10247 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010248 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010249
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010250 // Converting from one pointer type to another or between a pointer and an
10251 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010252 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010253 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10254 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010255 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 }
10257
10258 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010259 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010260 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010261
Chris Lattner58d74912008-03-12 17:45:29 +000010262 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10263 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010264 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010265 // won't be dropping them. Check that these extra arguments have attributes
10266 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010267 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10268 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010269 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010270 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010271 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010272 return false;
10273 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010274
Chris Lattner9fe38862003-06-19 17:00:31 +000010275 // Okay, we decided that this is a safe thing to do: go ahead and start
10276 // inserting cast instructions as necessary...
10277 std::vector<Value*> Args;
10278 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010279 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010280 attrVec.reserve(NumCommonArgs);
10281
10282 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010283 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010284
10285 // If the return value is not being used, the type may not be compatible
10286 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010287 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010288
10289 // Add the new return attributes.
10290 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010291 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010292
10293 AI = CS.arg_begin();
10294 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10295 const Type *ParamTy = FT->getParamType(i);
10296 if ((*AI)->getType() == ParamTy) {
10297 Args.push_back(*AI);
10298 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010299 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010300 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010301 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010302 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010303 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010304
10305 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010306 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010307 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010308 }
10309
10310 // If the function takes more arguments than the call was taking, add them
10311 // now...
10312 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010313 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010314
10315 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010316 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010317 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010318 cerr << "WARNING: While resolving call to function '"
10319 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010320 } else {
10321 // Add all of the arguments in their promoted form to the arg list...
10322 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10323 const Type *PTy = getPromotedType((*AI)->getType());
10324 if (PTy != (*AI)->getType()) {
10325 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010326 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10327 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010328 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010329 InsertNewInstBefore(Cast, *Caller);
10330 Args.push_back(Cast);
10331 } else {
10332 Args.push_back(*AI);
10333 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010334
Duncan Sandse1e520f2008-01-13 08:02:44 +000010335 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010336 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010337 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010338 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010339 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010340 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010341
Devang Patel19c87462008-09-26 22:53:05 +000010342 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10343 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10344
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010345 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010346 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010347
Devang Patel05988662008-09-25 21:00:45 +000010348 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010349
Chris Lattner9fe38862003-06-19 17:00:31 +000010350 Instruction *NC;
10351 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010352 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010353 Args.begin(), Args.end(),
10354 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010355 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010356 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010357 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010358 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10359 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010360 CallInst *CI = cast<CallInst>(Caller);
10361 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010362 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010363 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010364 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010365 }
10366
Chris Lattner6934a042007-02-11 01:23:03 +000010367 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010368 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010369 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010370 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010371 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010372 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010373 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010374
10375 // If this is an invoke instruction, we should insert it after the first
10376 // non-phi, instruction in the normal successor block.
10377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010378 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010379 InsertNewInstBefore(NC, *I);
10380 } else {
10381 // Otherwise, it's a call, just insert cast right after the call instr
10382 InsertNewInstBefore(NC, *Caller);
10383 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010384 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010385 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010386 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010387 }
10388 }
10389
10390 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10391 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010392 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010393 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010394 return true;
10395}
10396
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397// transformCallThroughTrampoline - Turn a call to a function created by the
10398// init_trampoline intrinsic into a direct call to the underlying function.
10399//
10400Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10401 Value *Callee = CS.getCalledValue();
10402 const PointerType *PTy = cast<PointerType>(Callee->getType());
10403 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010404 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010405
10406 // If the call already has the 'nest' attribute somewhere then give up -
10407 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010408 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410
10411 IntrinsicInst *Tramp =
10412 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10413
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010414 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010415 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10416 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10417
Devang Patel05988662008-09-25 21:00:45 +000010418 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010419 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 unsigned NestIdx = 1;
10421 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010422 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423
10424 // Look for a parameter marked with the 'nest' attribute.
10425 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10426 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010427 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 // Record the parameter type and any other attributes.
10429 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010430 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 break;
10432 }
10433
10434 if (NestTy) {
10435 Instruction *Caller = CS.getInstruction();
10436 std::vector<Value*> NewArgs;
10437 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10438
Devang Patel05988662008-09-25 21:00:45 +000010439 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010440 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // mean appending it. Likewise for attributes.
10444
Devang Patel19c87462008-09-26 22:53:05 +000010445 // Add any result attributes.
10446 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010447 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010448
Duncan Sandscdb6d922007-09-17 10:26:40 +000010449 {
10450 unsigned Idx = 1;
10451 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10452 do {
10453 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010454 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455 Value *NestVal = Tramp->getOperand(3);
10456 if (NestVal->getType() != NestTy)
10457 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10458 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010459 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460 }
10461
10462 if (I == E)
10463 break;
10464
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010465 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010466 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010467 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010468 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010469 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010470
10471 ++Idx, ++I;
10472 } while (1);
10473 }
10474
Devang Patel19c87462008-09-26 22:53:05 +000010475 // Add any function attributes.
10476 if (Attributes Attr = Attrs.getFnAttributes())
10477 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10478
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 // The trampoline may have been bitcast to a bogus type (FTy).
10480 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010481 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482
Duncan Sandscdb6d922007-09-17 10:26:40 +000010483 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010484 NewTypes.reserve(FTy->getNumParams()+1);
10485
Duncan Sandscdb6d922007-09-17 10:26:40 +000010486 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010487 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010488 {
10489 unsigned Idx = 1;
10490 FunctionType::param_iterator I = FTy->param_begin(),
10491 E = FTy->param_end();
10492
10493 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010494 if (Idx == NestIdx)
10495 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010496 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010497
10498 if (I == E)
10499 break;
10500
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010501 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010502 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010503
10504 ++Idx, ++I;
10505 } while (1);
10506 }
10507
10508 // Replace the trampoline call with a direct call. Let the generic
10509 // code sort out any function type mismatches.
10510 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010511 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10512 FTy->isVarArg());
10513 Constant *NewCallee =
10514 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10515 NestF : Context->getConstantExprBitCast(NestF,
10516 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010517 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010518
10519 Instruction *NewCaller;
10520 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010521 NewCaller = InvokeInst::Create(NewCallee,
10522 II->getNormalDest(), II->getUnwindDest(),
10523 NewArgs.begin(), NewArgs.end(),
10524 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010525 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010526 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010527 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010528 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10529 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010530 if (cast<CallInst>(Caller)->isTailCall())
10531 cast<CallInst>(NewCaller)->setTailCall();
10532 cast<CallInst>(NewCaller)->
10533 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010534 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010535 }
10536 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10537 Caller->replaceAllUsesWith(NewCaller);
10538 Caller->eraseFromParent();
10539 RemoveFromWorkList(Caller);
10540 return 0;
10541 }
10542 }
10543
10544 // Replace the trampoline call with a direct call. Since there is no 'nest'
10545 // parameter, there is no need to adjust the argument list. Let the generic
10546 // code sort out any function type mismatches.
10547 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010548 NestF->getType() == PTy ? NestF :
10549 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010550 CS.setCalledFunction(NewCallee);
10551 return CS.getInstruction();
10552}
10553
Chris Lattner7da52b22006-11-01 04:51:18 +000010554/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10555/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10556/// and a single binop.
10557Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10558 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010559 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010560 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010561 Value *LHSVal = FirstInst->getOperand(0);
10562 Value *RHSVal = FirstInst->getOperand(1);
10563
10564 const Type *LHSType = LHSVal->getType();
10565 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010566
10567 // Scan to see if all operands are the same opcode, all have one use, and all
10568 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010569 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010570 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010571 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010572 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010573 // types or GEP's with different index types.
10574 I->getOperand(0)->getType() != LHSType ||
10575 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010576 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010577
10578 // If they are CmpInst instructions, check their predicates
10579 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10580 if (cast<CmpInst>(I)->getPredicate() !=
10581 cast<CmpInst>(FirstInst)->getPredicate())
10582 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010583
10584 // Keep track of which operand needs a phi node.
10585 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10586 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010587 }
10588
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010589 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010590
Chris Lattner7da52b22006-11-01 04:51:18 +000010591 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010592 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010593 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010594 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010595 NewLHS = PHINode::Create(LHSType,
10596 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010597 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10598 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010599 InsertNewInstBefore(NewLHS, PN);
10600 LHSVal = NewLHS;
10601 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010602
10603 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010604 NewRHS = PHINode::Create(RHSType,
10605 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010606 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10607 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010608 InsertNewInstBefore(NewRHS, PN);
10609 RHSVal = NewRHS;
10610 }
10611
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010612 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010613 if (NewLHS || NewRHS) {
10614 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10615 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10616 if (NewLHS) {
10617 Value *NewInLHS = InInst->getOperand(0);
10618 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10619 }
10620 if (NewRHS) {
10621 Value *NewInRHS = InInst->getOperand(1);
10622 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10623 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010624 }
10625 }
10626
Chris Lattner7da52b22006-11-01 04:51:18 +000010627 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010628 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010629 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010630 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10631 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010632}
10633
Chris Lattner05f18922008-12-01 02:34:36 +000010634Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10635 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10636
10637 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10638 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010639 // This is true if all GEP bases are allocas and if all indices into them are
10640 // constants.
10641 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010642
10643 // Scan to see if all operands are the same opcode, all have one use, and all
10644 // kill their operands (i.e. the operands have one use).
10645 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10646 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10647 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10648 GEP->getNumOperands() != FirstInst->getNumOperands())
10649 return 0;
10650
Chris Lattner36d3e322009-02-21 00:46:50 +000010651 // Keep track of whether or not all GEPs are of alloca pointers.
10652 if (AllBasePointersAreAllocas &&
10653 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10654 !GEP->hasAllConstantIndices()))
10655 AllBasePointersAreAllocas = false;
10656
Chris Lattner05f18922008-12-01 02:34:36 +000010657 // Compare the operand lists.
10658 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10659 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10660 continue;
10661
10662 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10663 // if one of the PHIs has a constant for the index. The index may be
10664 // substantially cheaper to compute for the constants, so making it a
10665 // variable index could pessimize the path. This also handles the case
10666 // for struct indices, which must always be constant.
10667 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10668 isa<ConstantInt>(GEP->getOperand(op)))
10669 return 0;
10670
10671 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10672 return 0;
10673 FixedOperands[op] = 0; // Needs a PHI.
10674 }
10675 }
10676
Chris Lattner36d3e322009-02-21 00:46:50 +000010677 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010678 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010679 // offset calculation, but all the predecessors will have to materialize the
10680 // stack address into a register anyway. We'd actually rather *clone* the
10681 // load up into the predecessors so that we have a load of a gep of an alloca,
10682 // which can usually all be folded into the load.
10683 if (AllBasePointersAreAllocas)
10684 return 0;
10685
Chris Lattner05f18922008-12-01 02:34:36 +000010686 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10687 // that is variable.
10688 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10689
10690 bool HasAnyPHIs = false;
10691 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10692 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10693 Value *FirstOp = FirstInst->getOperand(i);
10694 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10695 FirstOp->getName()+".pn");
10696 InsertNewInstBefore(NewPN, PN);
10697
10698 NewPN->reserveOperandSpace(e);
10699 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10700 OperandPhis[i] = NewPN;
10701 FixedOperands[i] = NewPN;
10702 HasAnyPHIs = true;
10703 }
10704
10705
10706 // Add all operands to the new PHIs.
10707 if (HasAnyPHIs) {
10708 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10709 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10710 BasicBlock *InBB = PN.getIncomingBlock(i);
10711
10712 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10713 if (PHINode *OpPhi = OperandPhis[op])
10714 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10715 }
10716 }
10717
10718 Value *Base = FixedOperands[0];
10719 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10720 FixedOperands.end());
10721}
10722
10723
Chris Lattner21550882009-02-23 05:56:17 +000010724/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10725/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010726/// obvious the value of the load is not changed from the point of the load to
10727/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010728///
10729/// Finally, it is safe, but not profitable, to sink a load targetting a
10730/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10731/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010732static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010733 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10734
10735 for (++BBI; BBI != E; ++BBI)
10736 if (BBI->mayWriteToMemory())
10737 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010738
10739 // Check for non-address taken alloca. If not address-taken already, it isn't
10740 // profitable to do this xform.
10741 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10742 bool isAddressTaken = false;
10743 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10744 UI != E; ++UI) {
10745 if (isa<LoadInst>(UI)) continue;
10746 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10747 // If storing TO the alloca, then the address isn't taken.
10748 if (SI->getOperand(1) == AI) continue;
10749 }
10750 isAddressTaken = true;
10751 break;
10752 }
10753
Chris Lattner36d3e322009-02-21 00:46:50 +000010754 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010755 return false;
10756 }
10757
Chris Lattner36d3e322009-02-21 00:46:50 +000010758 // If this load is a load from a GEP with a constant offset from an alloca,
10759 // then we don't want to sink it. In its present form, it will be
10760 // load [constant stack offset]. Sinking it will cause us to have to
10761 // materialize the stack addresses in each predecessor in a register only to
10762 // do a shared load from register in the successor.
10763 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10764 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10765 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10766 return false;
10767
Chris Lattner76c73142006-11-01 07:13:54 +000010768 return true;
10769}
10770
Chris Lattner9fe38862003-06-19 17:00:31 +000010771
Chris Lattnerbac32862004-11-14 19:13:23 +000010772// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10773// operator and they all are only used by the PHI, PHI together their
10774// inputs, and do the operation once, to the result of the PHI.
10775Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10776 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10777
10778 // Scan the instruction, looking for input operations that can be folded away.
10779 // If all input operands to the phi are the same instruction (e.g. a cast from
10780 // the same type or "+42") we can pull the operation through the PHI, reducing
10781 // code size and simplifying code.
10782 Constant *ConstantOp = 0;
10783 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010784 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010785 if (isa<CastInst>(FirstInst)) {
10786 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010787 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010788 // Can fold binop, compare or shift here if the RHS is a constant,
10789 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010790 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010791 if (ConstantOp == 0)
10792 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010793 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10794 isVolatile = LI->isVolatile();
10795 // We can't sink the load if the loaded value could be modified between the
10796 // load and the PHI.
10797 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010798 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010799 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010800
10801 // If the PHI is of volatile loads and the load block has multiple
10802 // successors, sinking it would remove a load of the volatile value from
10803 // the path through the other successor.
10804 if (isVolatile &&
10805 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10806 return 0;
10807
Chris Lattner9c080502006-11-01 07:43:41 +000010808 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010809 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010810 } else {
10811 return 0; // Cannot fold this operation.
10812 }
10813
10814 // Check to see if all arguments are the same operation.
10815 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10817 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010818 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010819 return 0;
10820 if (CastSrcTy) {
10821 if (I->getOperand(0)->getType() != CastSrcTy)
10822 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010823 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010824 // We can't sink the load if the loaded value could be modified between
10825 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010826 if (LI->isVolatile() != isVolatile ||
10827 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010828 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010829 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010830
Chris Lattner71042962008-07-08 17:18:32 +000010831 // If the PHI is of volatile loads and the load block has multiple
10832 // successors, sinking it would remove a load of the volatile value from
10833 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010834 if (isVolatile &&
10835 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10836 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010837
Chris Lattnerbac32862004-11-14 19:13:23 +000010838 } else if (I->getOperand(1) != ConstantOp) {
10839 return 0;
10840 }
10841 }
10842
10843 // Okay, they are all the same operation. Create a new PHI node of the
10844 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010845 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10846 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010847 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010848
10849 Value *InVal = FirstInst->getOperand(0);
10850 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010851
10852 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010853 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10854 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10855 if (NewInVal != InVal)
10856 InVal = 0;
10857 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10858 }
10859
10860 Value *PhiVal;
10861 if (InVal) {
10862 // The new PHI unions all of the same values together. This is really
10863 // common, so we handle it intelligently here for compile-time speed.
10864 PhiVal = InVal;
10865 delete NewPN;
10866 } else {
10867 InsertNewInstBefore(NewPN, PN);
10868 PhiVal = NewPN;
10869 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010870
Chris Lattnerbac32862004-11-14 19:13:23 +000010871 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010872 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010873 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010874 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010875 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010876 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010877 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010878 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010879 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10880
10881 // If this was a volatile load that we are merging, make sure to loop through
10882 // and mark all the input loads as non-volatile. If we don't do this, we will
10883 // insert a new volatile load and the old ones will not be deletable.
10884 if (isVolatile)
10885 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10886 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10887
10888 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010889}
Chris Lattnera1be5662002-05-02 17:06:02 +000010890
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010891/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10892/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010893static bool DeadPHICycle(PHINode *PN,
10894 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010895 if (PN->use_empty()) return true;
10896 if (!PN->hasOneUse()) return false;
10897
10898 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010899 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010900 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010901
10902 // Don't scan crazily complex things.
10903 if (PotentiallyDeadPHIs.size() == 16)
10904 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010905
10906 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10907 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010908
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010909 return false;
10910}
10911
Chris Lattnercf5008a2007-11-06 21:52:06 +000010912/// PHIsEqualValue - Return true if this phi node is always equal to
10913/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10914/// z = some value; x = phi (y, z); y = phi (x, z)
10915static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10916 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10917 // See if we already saw this PHI node.
10918 if (!ValueEqualPHIs.insert(PN))
10919 return true;
10920
10921 // Don't scan crazily complex things.
10922 if (ValueEqualPHIs.size() == 16)
10923 return false;
10924
10925 // Scan the operands to see if they are either phi nodes or are equal to
10926 // the value.
10927 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10928 Value *Op = PN->getIncomingValue(i);
10929 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10930 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10931 return false;
10932 } else if (Op != NonPhiInVal)
10933 return false;
10934 }
10935
10936 return true;
10937}
10938
10939
Chris Lattner473945d2002-05-06 18:06:38 +000010940// PHINode simplification
10941//
Chris Lattner7e708292002-06-25 16:13:24 +000010942Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010943 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010944 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010945
Owen Anderson7e057142006-07-10 22:03:18 +000010946 if (Value *V = PN.hasConstantValue())
10947 return ReplaceInstUsesWith(PN, V);
10948
Owen Anderson7e057142006-07-10 22:03:18 +000010949 // If all PHI operands are the same operation, pull them through the PHI,
10950 // reducing code size.
10951 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010952 isa<Instruction>(PN.getIncomingValue(1)) &&
10953 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10954 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10955 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10956 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010957 PN.getIncomingValue(0)->hasOneUse())
10958 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10959 return Result;
10960
10961 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10962 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10963 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010964 if (PN.hasOneUse()) {
10965 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10966 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010967 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010968 PotentiallyDeadPHIs.insert(&PN);
10969 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010970 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010971 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010972
10973 // If this phi has a single use, and if that use just computes a value for
10974 // the next iteration of a loop, delete the phi. This occurs with unused
10975 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10976 // common case here is good because the only other things that catch this
10977 // are induction variable analysis (sometimes) and ADCE, which is only run
10978 // late.
10979 if (PHIUser->hasOneUse() &&
10980 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10981 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010982 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010983 }
10984 }
Owen Anderson7e057142006-07-10 22:03:18 +000010985
Chris Lattnercf5008a2007-11-06 21:52:06 +000010986 // We sometimes end up with phi cycles that non-obviously end up being the
10987 // same value, for example:
10988 // z = some value; x = phi (y, z); y = phi (x, z)
10989 // where the phi nodes don't necessarily need to be in the same block. Do a
10990 // quick check to see if the PHI node only contains a single non-phi value, if
10991 // so, scan to see if the phi cycle is actually equal to that value.
10992 {
10993 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10994 // Scan for the first non-phi operand.
10995 while (InValNo != NumOperandVals &&
10996 isa<PHINode>(PN.getIncomingValue(InValNo)))
10997 ++InValNo;
10998
10999 if (InValNo != NumOperandVals) {
11000 Value *NonPhiInVal = PN.getOperand(InValNo);
11001
11002 // Scan the rest of the operands to see if there are any conflicts, if so
11003 // there is no need to recursively scan other phis.
11004 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11005 Value *OpVal = PN.getIncomingValue(InValNo);
11006 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11007 break;
11008 }
11009
11010 // If we scanned over all operands, then we have one unique value plus
11011 // phi values. Scan PHI nodes to see if they all merge in each other or
11012 // the value.
11013 if (InValNo == NumOperandVals) {
11014 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11015 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11016 return ReplaceInstUsesWith(PN, NonPhiInVal);
11017 }
11018 }
11019 }
Chris Lattner60921c92003-12-19 05:58:40 +000011020 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011021}
11022
Reid Spencer17212df2006-12-12 09:18:51 +000011023static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11024 Instruction *InsertPoint,
11025 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000011026 unsigned PtrSize = DTy->getScalarSizeInBits();
11027 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000011028 // We must cast correctly to the pointer type. Ensure that we
11029 // sign extend the integer value if it is smaller as this is
11030 // used for address computation.
11031 Instruction::CastOps opcode =
11032 (VTySize < PtrSize ? Instruction::SExt :
11033 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11034 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000011035}
11036
Chris Lattnera1be5662002-05-02 17:06:02 +000011037
Chris Lattner7e708292002-06-25 16:13:24 +000011038Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011039 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011040 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011041 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011042 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011043 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011044
Chris Lattnere87597f2004-10-16 18:11:37 +000011045 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011046 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011047
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011048 bool HasZeroPointerIndex = false;
11049 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11050 HasZeroPointerIndex = C->isNullValue();
11051
11052 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011053 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011054
Chris Lattner28977af2004-04-05 01:30:19 +000011055 // Eliminate unneeded casts for indices.
11056 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011057
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011058 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011059 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11060 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011061 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011062 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011063 if (CI->getOpcode() == Instruction::ZExt ||
11064 CI->getOpcode() == Instruction::SExt) {
11065 const Type *SrcTy = CI->getOperand(0)->getType();
11066 // We can eliminate a cast from i32 to i64 iff the target
11067 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011068 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011069 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011070 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011071 }
11072 }
11073 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011074 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011075 // to what we need. If narrower, sign-extend it to what we need.
11076 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011077 // insert it. This explicit cast can make subsequent optimizations more
11078 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011079 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011080 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011081 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011082 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011083 MadeChange = true;
11084 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011085 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11086 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011087 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011088 MadeChange = true;
11089 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011090 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11091 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011092 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011093 MadeChange = true;
11094 } else {
11095 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11096 GEP);
11097 *i = Op;
11098 MadeChange = true;
11099 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011100 }
Chris Lattner28977af2004-04-05 01:30:19 +000011101 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011102 }
Chris Lattner28977af2004-04-05 01:30:19 +000011103 if (MadeChange) return &GEP;
11104
Chris Lattner90ac28c2002-08-02 19:29:35 +000011105 // Combine Indices - If the source pointer to this getelementptr instruction
11106 // is a getelementptr instruction, combine the indices of the two
11107 // getelementptr instructions into a single instruction.
11108 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011109 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011110 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011111 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011112
11113 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011114 // Note that if our source is a gep chain itself that we wait for that
11115 // chain to be resolved before we perform this transformation. This
11116 // avoids us creating a TON of code in some cases.
11117 //
11118 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11119 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11120 return 0; // Wait until our source is folded to completion.
11121
Chris Lattner72588fc2007-02-15 22:48:32 +000011122 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011123
11124 // Find out whether the last index in the source GEP is a sequential idx.
11125 bool EndsWithSequential = false;
11126 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11127 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011128 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011129
Chris Lattner90ac28c2002-08-02 19:29:35 +000011130 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011131 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011132 // Replace: gep (gep %P, long B), long A, ...
11133 // With: T = long A+B; gep %P, T, ...
11134 //
Chris Lattner620ce142004-05-07 22:09:22 +000011135 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011136 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011137 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011138 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011139 Sum = SO1;
11140 } else {
11141 // If they aren't the same type, convert both to an integer of the
11142 // target's pointer size.
11143 if (SO1->getType() != GO1->getType()) {
11144 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011145 SO1 =
11146 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011147 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011148 GO1 =
11149 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011150 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011151 unsigned PS = TD->getPointerSizeInBits();
11152 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011153 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011154 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011155
Duncan Sands514ab342007-11-01 20:53:16 +000011156 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011157 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011158 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011159 } else {
11160 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011161 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11162 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011163 }
11164 }
11165 }
Chris Lattner620ce142004-05-07 22:09:22 +000011166 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011167 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11168 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011169 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011170 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011171 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011172 }
Chris Lattner28977af2004-04-05 01:30:19 +000011173 }
Chris Lattner620ce142004-05-07 22:09:22 +000011174
11175 // Recycle the GEP we already have if possible.
11176 if (SrcGEPOperands.size() == 2) {
11177 GEP.setOperand(0, SrcGEPOperands[0]);
11178 GEP.setOperand(1, Sum);
11179 return &GEP;
11180 } else {
11181 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11182 SrcGEPOperands.end()-1);
11183 Indices.push_back(Sum);
11184 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11185 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011186 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011187 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011188 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011189 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011190 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11191 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011192 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11193 }
11194
11195 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011196 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11197 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011198
Chris Lattner620ce142004-05-07 22:09:22 +000011199 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011200 // GEP of global variable. If all of the indices for this GEP are
11201 // constants, we can promote this to a constexpr instead of an instruction.
11202
11203 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011204 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011205 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11206 for (; I != E && isa<Constant>(*I); ++I)
11207 Indices.push_back(cast<Constant>(*I));
11208
11209 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011210 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011211 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011212
11213 // Replace all uses of the GEP with the new constexpr...
11214 return ReplaceInstUsesWith(GEP, CE);
11215 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011216 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011217 if (!isa<PointerType>(X->getType())) {
11218 // Not interesting. Source pointer must be a cast from pointer.
11219 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011220 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11221 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011222 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011223 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11224 // into : GEP i8* X, ...
11225 //
Chris Lattnereed48272005-09-13 00:40:14 +000011226 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011227 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11228 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011229 if (const ArrayType *CATy =
11230 dyn_cast<ArrayType>(CPTy->getElementType())) {
11231 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11232 if (CATy->getElementType() == XTy->getElementType()) {
11233 // -> GEP i8* X, ...
11234 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11235 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11236 GEP.getName());
11237 } else if (const ArrayType *XATy =
11238 dyn_cast<ArrayType>(XTy->getElementType())) {
11239 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011240 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011241 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011242 // At this point, we know that the cast source type is a pointer
11243 // to an array of the same type as the destination pointer
11244 // array. Because the array type is never stepped over (there
11245 // is a leading zero) we can fold the cast into this GEP.
11246 GEP.setOperand(0, X);
11247 return &GEP;
11248 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011249 }
11250 }
Chris Lattnereed48272005-09-13 00:40:14 +000011251 } else if (GEP.getNumOperands() == 2) {
11252 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011253 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11254 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011255 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11256 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11257 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011258 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11259 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011260 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011261 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011262 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011263 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011264 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011265 // V and GEP are both pointer types --> BitCast
11266 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011267 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011268
11269 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011270 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011271 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011272 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011273
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011274 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011275 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011276 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011277
11278 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11279 // allow either a mul, shift, or constant here.
11280 Value *NewIdx = 0;
11281 ConstantInt *Scale = 0;
11282 if (ArrayEltSize == 1) {
11283 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011284 Scale =
11285 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011286 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011287 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011288 Scale = CI;
11289 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11290 if (Inst->getOpcode() == Instruction::Shl &&
11291 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011292 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11293 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011294 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011295 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011296 NewIdx = Inst->getOperand(0);
11297 } else if (Inst->getOpcode() == Instruction::Mul &&
11298 isa<ConstantInt>(Inst->getOperand(1))) {
11299 Scale = cast<ConstantInt>(Inst->getOperand(1));
11300 NewIdx = Inst->getOperand(0);
11301 }
11302 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011303
Chris Lattner7835cdd2005-09-13 18:36:04 +000011304 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011305 // out, perform the transformation. Note, we don't know whether Scale is
11306 // signed or not. We'll use unsigned version of division/modulo
11307 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011308 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011309 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011310 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011311 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011312 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011313 Constant *C =
11314 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011315 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011316 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011317 NewIdx = InsertNewInstBefore(Sc, GEP);
11318 }
11319
11320 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011321 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011322 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011323 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011324 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011325 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011326 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11327 // The NewGEP must be pointer typed, so must the old one -> BitCast
11328 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011329 }
11330 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011331 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011332 }
Chris Lattner58407792009-01-09 04:53:57 +000011333
Chris Lattner46cd5a12009-01-09 05:44:56 +000011334 /// See if we can simplify:
11335 /// X = bitcast A to B*
11336 /// Y = gep X, <...constant indices...>
11337 /// into a gep of the original struct. This is important for SROA and alias
11338 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011339 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011340 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11341 // Determine how much the GEP moves the pointer. We are guaranteed to get
11342 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011343 ConstantInt *OffsetV =
11344 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011345 int64_t Offset = OffsetV->getSExtValue();
11346
11347 // If this GEP instruction doesn't move the pointer, just replace the GEP
11348 // with a bitcast of the real input to the dest type.
11349 if (Offset == 0) {
11350 // If the bitcast is of an allocation, and the allocation will be
11351 // converted to match the type of the cast, don't touch this.
11352 if (isa<AllocationInst>(BCI->getOperand(0))) {
11353 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11354 if (Instruction *I = visitBitCast(*BCI)) {
11355 if (I != BCI) {
11356 I->takeName(BCI);
11357 BCI->getParent()->getInstList().insert(BCI, I);
11358 ReplaceInstUsesWith(*BCI, I);
11359 }
11360 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011361 }
Chris Lattner58407792009-01-09 04:53:57 +000011362 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011363 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011364 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011365
11366 // Otherwise, if the offset is non-zero, we need to find out if there is a
11367 // field at Offset in 'A's type. If so, we can pull the cast through the
11368 // GEP.
11369 SmallVector<Value*, 8> NewIndices;
11370 const Type *InTy =
11371 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011372 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011373 Instruction *NGEP =
11374 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11375 NewIndices.end());
11376 if (NGEP->getType() == GEP.getType()) return NGEP;
11377 InsertNewInstBefore(NGEP, GEP);
11378 NGEP->takeName(&GEP);
11379 return new BitCastInst(NGEP, GEP.getType());
11380 }
Chris Lattner58407792009-01-09 04:53:57 +000011381 }
11382 }
11383
Chris Lattner8a2a3112001-12-14 16:52:21 +000011384 return 0;
11385}
11386
Chris Lattner0864acf2002-11-04 16:18:53 +000011387Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11388 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011389 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011390 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11391 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011392 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011393 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011394
11395 // Create and insert the replacement instruction...
11396 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011397 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011398 else {
11399 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011400 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011401 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011402
11403 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011404
Chris Lattner0864acf2002-11-04 16:18:53 +000011405 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011406 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011407 //
11408 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011409 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011410
11411 // Now that I is pointing to the first non-allocation-inst in the block,
11412 // insert our getelementptr instruction...
11413 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011414 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011415 Value *Idx[2];
11416 Idx[0] = NullIdx;
11417 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011418 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11419 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011420
11421 // Now make everything use the getelementptr instead of the original
11422 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011423 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011424 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011425 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011426 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011427 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011428
Dan Gohman6893cd72009-01-13 20:18:38 +000011429 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11430 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011431 // Note that we only do this for alloca's, because malloc should allocate
11432 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011433 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011434 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011435
11436 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11437 if (AI.getAlignment() == 0)
11438 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11439 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011440
Chris Lattner0864acf2002-11-04 16:18:53 +000011441 return 0;
11442}
11443
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011444Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11445 Value *Op = FI.getOperand(0);
11446
Chris Lattner17be6352004-10-18 02:59:09 +000011447 // free undef -> unreachable.
11448 if (isa<UndefValue>(Op)) {
11449 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011450 new StoreInst(Context->getConstantIntTrue(),
11451 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011452 return EraseInstFromFunction(FI);
11453 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011454
Chris Lattner6160e852004-02-28 04:57:37 +000011455 // If we have 'free null' delete the instruction. This can happen in stl code
11456 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011457 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011458 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011459
11460 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11461 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11462 FI.setOperand(0, CI->getOperand(0));
11463 return &FI;
11464 }
11465
11466 // Change free (gep X, 0,0,0,0) into free(X)
11467 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11468 if (GEPI->hasAllZeroIndices()) {
11469 AddToWorkList(GEPI);
11470 FI.setOperand(0, GEPI->getOperand(0));
11471 return &FI;
11472 }
11473 }
11474
11475 // Change free(malloc) into nothing, if the malloc has a single use.
11476 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11477 if (MI->hasOneUse()) {
11478 EraseInstFromFunction(FI);
11479 return EraseInstFromFunction(*MI);
11480 }
Chris Lattner6160e852004-02-28 04:57:37 +000011481
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011482 return 0;
11483}
11484
11485
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011486/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011487static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011488 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011489 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011490 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011491 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011492
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011493 if (TD) {
11494 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11495 // Instead of loading constant c string, use corresponding integer value
11496 // directly if string length is small enough.
11497 std::string Str;
11498 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11499 unsigned len = Str.length();
11500 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11501 unsigned numBits = Ty->getPrimitiveSizeInBits();
11502 // Replace LI with immediate integer store.
11503 if ((numBits >> 3) == len + 1) {
11504 APInt StrVal(numBits, 0);
11505 APInt SingleChar(numBits, 0);
11506 if (TD->isLittleEndian()) {
11507 for (signed i = len-1; i >= 0; i--) {
11508 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11509 StrVal = (StrVal << 8) | SingleChar;
11510 }
11511 } else {
11512 for (unsigned i = 0; i < len; i++) {
11513 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11514 StrVal = (StrVal << 8) | SingleChar;
11515 }
11516 // Append NULL at the end.
11517 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011518 StrVal = (StrVal << 8) | SingleChar;
11519 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011520 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011521 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011522 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011523 }
11524 }
11525 }
11526
Mon P Wang6753f952009-02-07 22:19:29 +000011527 const PointerType *DestTy = cast<PointerType>(CI->getType());
11528 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011529 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011530
11531 // If the address spaces don't match, don't eliminate the cast.
11532 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11533 return 0;
11534
Chris Lattnerb89e0712004-07-13 01:49:43 +000011535 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011536
Reid Spencer42230162007-01-22 05:51:25 +000011537 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011538 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011539 // If the source is an array, the code below will not succeed. Check to
11540 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11541 // constants.
11542 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11543 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11544 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011545 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011546 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11547 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011548 SrcTy = cast<PointerType>(CastOp->getType());
11549 SrcPTy = SrcTy->getElementType();
11550 }
11551
Reid Spencer42230162007-01-22 05:51:25 +000011552 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011553 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011554 // Do not allow turning this into a load of an integer, which is then
11555 // casted to a pointer, this pessimizes pointer analysis a lot.
11556 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011557 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11558 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011559
Chris Lattnerf9527852005-01-31 04:50:46 +000011560 // Okay, we are casting from one integer or pointer type to another of
11561 // the same size. Instead of casting the pointer before the load, cast
11562 // the result of the loaded value.
11563 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11564 CI->getName(),
11565 LI.isVolatile()),LI);
11566 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011567 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011568 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011569 }
11570 }
11571 return 0;
11572}
11573
Chris Lattner833b8a42003-06-26 05:06:25 +000011574Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11575 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011576
Dan Gohman9941f742007-07-20 16:34:21 +000011577 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011578 unsigned KnownAlign =
11579 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011580 if (KnownAlign >
11581 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11582 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011583 LI.setAlignment(KnownAlign);
11584
Chris Lattner37366c12005-05-01 04:24:53 +000011585 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011586 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011587 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011588 return Res;
11589
11590 // None of the following transforms are legal for volatile loads.
11591 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011592
Dan Gohman2276a7b2008-10-15 23:19:35 +000011593 // Do really simple store-to-load forwarding and load CSE, to catch cases
11594 // where there are several consequtive memory accesses to the same location,
11595 // separated by a few arithmetic operations.
11596 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011597 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11598 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011599
Christopher Lambb15147e2007-12-29 07:56:53 +000011600 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11601 const Value *GEPI0 = GEPI->getOperand(0);
11602 // TODO: Consider a target hook for valid address spaces for this xform.
11603 if (isa<ConstantPointerNull>(GEPI0) &&
11604 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011605 // Insert a new store to null instruction before the load to indicate
11606 // that this code is not reachable. We do this instead of inserting
11607 // an unreachable instruction directly because we cannot modify the
11608 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011609 new StoreInst(Context->getUndef(LI.getType()),
11610 Context->getNullValue(Op->getType()), &LI);
11611 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011612 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011613 }
Chris Lattner37366c12005-05-01 04:24:53 +000011614
Chris Lattnere87597f2004-10-16 18:11:37 +000011615 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011616 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011617 // TODO: Consider a target hook for valid address spaces for this xform.
11618 if (isa<UndefValue>(C) || (C->isNullValue() &&
11619 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011620 // Insert a new store to null instruction before the load to indicate that
11621 // this code is not reachable. We do this instead of inserting an
11622 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011623 new StoreInst(Context->getUndef(LI.getType()),
11624 Context->getNullValue(Op->getType()), &LI);
11625 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011626 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011627
Chris Lattnere87597f2004-10-16 18:11:37 +000011628 // Instcombine load (constant global) into the value loaded.
11629 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011630 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011631 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011632
Chris Lattnere87597f2004-10-16 18:11:37 +000011633 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011635 if (CE->getOpcode() == Instruction::GetElementPtr) {
11636 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011637 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011638 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011639 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11640 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011641 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011642 if (CE->getOperand(0)->isNullValue()) {
11643 // Insert a new store to null instruction before the load to indicate
11644 // that this code is not reachable. We do this instead of inserting
11645 // an unreachable instruction directly because we cannot modify the
11646 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011647 new StoreInst(Context->getUndef(LI.getType()),
11648 Context->getNullValue(Op->getType()), &LI);
11649 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011650 }
11651
Reid Spencer3da59db2006-11-27 01:05:10 +000011652 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011653 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011654 return Res;
11655 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011656 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011657 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011658
11659 // If this load comes from anywhere in a constant global, and if the global
11660 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011661 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011662 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011663 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011664 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011665 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011666 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011667 }
11668 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011669
Chris Lattner37366c12005-05-01 04:24:53 +000011670 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011671 // Change select and PHI nodes to select values instead of addresses: this
11672 // helps alias analysis out a lot, allows many others simplifications, and
11673 // exposes redundancy in the code.
11674 //
11675 // Note that we cannot do the transformation unless we know that the
11676 // introduced loads cannot trap! Something like this is valid as long as
11677 // the condition is always false: load (select bool %C, int* null, int* %G),
11678 // but it would not be valid if we transformed it to load from null
11679 // unconditionally.
11680 //
11681 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11682 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011683 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11684 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011685 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011686 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011687 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011688 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011689 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011690 }
11691
Chris Lattner684fe212004-09-23 15:46:00 +000011692 // load (select (cond, null, P)) -> load P
11693 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11694 if (C->isNullValue()) {
11695 LI.setOperand(0, SI->getOperand(2));
11696 return &LI;
11697 }
11698
11699 // load (select (cond, P, null)) -> load P
11700 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11701 if (C->isNullValue()) {
11702 LI.setOperand(0, SI->getOperand(1));
11703 return &LI;
11704 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011705 }
11706 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011707 return 0;
11708}
11709
Reid Spencer55af2b52007-01-19 21:20:31 +000011710/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011711/// when possible. This makes it generally easy to do alias analysis and/or
11712/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011713static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11714 User *CI = cast<User>(SI.getOperand(1));
11715 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011716 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011717
11718 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011719 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11720 if (SrcTy == 0) return 0;
11721
11722 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011723
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011724 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11725 return 0;
11726
Chris Lattner3914f722009-01-24 01:00:13 +000011727 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11728 /// to its first element. This allows us to handle things like:
11729 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11730 /// on 32-bit hosts.
11731 SmallVector<Value*, 4> NewGEPIndices;
11732
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011733 // If the source is an array, the code below will not succeed. Check to
11734 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11735 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011736 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11737 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011738 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011739 NewGEPIndices.push_back(Zero);
11740
11741 while (1) {
11742 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011743 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011744 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011745 NewGEPIndices.push_back(Zero);
11746 SrcPTy = STy->getElementType(0);
11747 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11748 NewGEPIndices.push_back(Zero);
11749 SrcPTy = ATy->getElementType();
11750 } else {
11751 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011752 }
Chris Lattner3914f722009-01-24 01:00:13 +000011753 }
11754
Owen Andersond672ecb2009-07-03 00:17:18 +000011755 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011756 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011757
11758 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11759 return 0;
11760
Chris Lattner71759c42009-01-16 20:12:52 +000011761 // If the pointers point into different address spaces or if they point to
11762 // values with different sizes, we can't do the transformation.
11763 if (SrcTy->getAddressSpace() !=
11764 cast<PointerType>(CI->getType())->getAddressSpace() ||
11765 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011766 IC.getTargetData().getTypeSizeInBits(DestPTy))
11767 return 0;
11768
11769 // Okay, we are casting from one integer or pointer type to another of
11770 // the same size. Instead of casting the pointer before
11771 // the store, cast the value to be stored.
11772 Value *NewCast;
11773 Value *SIOp0 = SI.getOperand(0);
11774 Instruction::CastOps opcode = Instruction::BitCast;
11775 const Type* CastSrcTy = SIOp0->getType();
11776 const Type* CastDstTy = SrcPTy;
11777 if (isa<PointerType>(CastDstTy)) {
11778 if (CastSrcTy->isInteger())
11779 opcode = Instruction::IntToPtr;
11780 } else if (isa<IntegerType>(CastDstTy)) {
11781 if (isa<PointerType>(SIOp0->getType()))
11782 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011783 }
Chris Lattner3914f722009-01-24 01:00:13 +000011784
11785 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11786 // emit a GEP to index into its first field.
11787 if (!NewGEPIndices.empty()) {
11788 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011789 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011790 NewGEPIndices.size());
11791 else
11792 CastOp = IC.InsertNewInstBefore(
11793 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11794 NewGEPIndices.end()), SI);
11795 }
11796
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011797 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011798 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011799 else
11800 NewCast = IC.InsertNewInstBefore(
11801 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11802 SI);
11803 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011804}
11805
Chris Lattner4aebaee2008-11-27 08:56:30 +000011806/// equivalentAddressValues - Test if A and B will obviously have the same
11807/// value. This includes recognizing that %t0 and %t1 will have the same
11808/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011809/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011810/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011811/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011812/// %t2 = load i32* %t1
11813///
11814static bool equivalentAddressValues(Value *A, Value *B) {
11815 // Test if the values are trivially equivalent.
11816 if (A == B) return true;
11817
11818 // Test if the values come form identical arithmetic instructions.
11819 if (isa<BinaryOperator>(A) ||
11820 isa<CastInst>(A) ||
11821 isa<PHINode>(A) ||
11822 isa<GetElementPtrInst>(A))
11823 if (Instruction *BI = dyn_cast<Instruction>(B))
11824 if (cast<Instruction>(A)->isIdenticalTo(BI))
11825 return true;
11826
11827 // Otherwise they may not be equivalent.
11828 return false;
11829}
11830
Dale Johannesen4945c652009-03-03 21:26:39 +000011831// If this instruction has two uses, one of which is a llvm.dbg.declare,
11832// return the llvm.dbg.declare.
11833DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11834 if (!V->hasNUses(2))
11835 return 0;
11836 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11837 UI != E; ++UI) {
11838 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11839 return DI;
11840 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11841 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11842 return DI;
11843 }
11844 }
11845 return 0;
11846}
11847
Chris Lattner2f503e62005-01-31 05:36:43 +000011848Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11849 Value *Val = SI.getOperand(0);
11850 Value *Ptr = SI.getOperand(1);
11851
11852 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011853 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011854 ++NumCombined;
11855 return 0;
11856 }
Chris Lattner836692d2007-01-15 06:51:56 +000011857
11858 // If the RHS is an alloca with a single use, zapify the store, making the
11859 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011860 // If the RHS is an alloca with a two uses, the other one being a
11861 // llvm.dbg.declare, zapify the store and the declare, making the
11862 // alloca dead. We must do this to prevent declare's from affecting
11863 // codegen.
11864 if (!SI.isVolatile()) {
11865 if (Ptr->hasOneUse()) {
11866 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011871 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11872 if (isa<AllocaInst>(GEP->getOperand(0))) {
11873 if (GEP->getOperand(0)->hasOneUse()) {
11874 EraseInstFromFunction(SI);
11875 ++NumCombined;
11876 return 0;
11877 }
11878 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11879 EraseInstFromFunction(*DI);
11880 EraseInstFromFunction(SI);
11881 ++NumCombined;
11882 return 0;
11883 }
11884 }
11885 }
11886 }
11887 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11888 EraseInstFromFunction(*DI);
11889 EraseInstFromFunction(SI);
11890 ++NumCombined;
11891 return 0;
11892 }
Chris Lattner836692d2007-01-15 06:51:56 +000011893 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011894
Dan Gohman9941f742007-07-20 16:34:21 +000011895 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011896 unsigned KnownAlign =
11897 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011898 if (KnownAlign >
11899 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011901 SI.setAlignment(KnownAlign);
11902
Dale Johannesenacb51a32009-03-03 01:43:03 +000011903 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011904 // stores to the same location, separated by a few arithmetic operations. This
11905 // situation often occurs with bitfield accesses.
11906 BasicBlock::iterator BBI = &SI;
11907 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11908 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011909 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011910 // Don't count debug info directives, lest they affect codegen,
11911 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11912 // It is necessary for correctness to skip those that feed into a
11913 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011914 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011915 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011916 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011917 continue;
11918 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011919
11920 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11921 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011922 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11923 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011924 ++NumDeadStore;
11925 ++BBI;
11926 EraseInstFromFunction(*PrevSI);
11927 continue;
11928 }
11929 break;
11930 }
11931
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011932 // If this is a load, we have to stop. However, if the loaded value is from
11933 // the pointer we're loading and is producing the pointer we're storing,
11934 // then *this* store is dead (X = load P; store X -> P).
11935 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011936 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11937 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011938 EraseInstFromFunction(SI);
11939 ++NumCombined;
11940 return 0;
11941 }
11942 // Otherwise, this is a load from some other location. Stores before it
11943 // may not be dead.
11944 break;
11945 }
11946
Chris Lattner9ca96412006-02-08 03:25:32 +000011947 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011948 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011949 break;
11950 }
11951
11952
11953 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011954
11955 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011956 if (isa<ConstantPointerNull>(Ptr) &&
11957 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011958 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011959 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011960 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011961 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011962 ++NumCombined;
11963 }
11964 return 0; // Do not modify these!
11965 }
11966
11967 // store undef, Ptr -> noop
11968 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011969 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011970 ++NumCombined;
11971 return 0;
11972 }
11973
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011974 // If the pointer destination is a cast, see if we can fold the cast into the
11975 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011976 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011977 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11978 return Res;
11979 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011980 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011981 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11982 return Res;
11983
Chris Lattner408902b2005-09-12 23:23:25 +000011984
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011985 // If this store is the last instruction in the basic block (possibly
11986 // excepting debug info instructions and the pointer bitcasts that feed
11987 // into them), and if the block ends with an unconditional branch, try
11988 // to move it to the successor block.
11989 BBI = &SI;
11990 do {
11991 ++BBI;
11992 } while (isa<DbgInfoIntrinsic>(BBI) ||
11993 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011994 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995 if (BI->isUnconditional())
11996 if (SimplifyStoreAtEndOfBlock(SI))
11997 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011998
Chris Lattner2f503e62005-01-31 05:36:43 +000011999 return 0;
12000}
12001
Chris Lattner3284d1f2007-04-15 00:07:55 +000012002/// SimplifyStoreAtEndOfBlock - Turn things like:
12003/// if () { *P = v1; } else { *P = v2 }
12004/// into a phi node with a store in the successor.
12005///
Chris Lattner31755a02007-04-15 01:02:18 +000012006/// Simplify things like:
12007/// *P = v1; if () { *P = v2; }
12008/// into a phi node with a store in the successor.
12009///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12011 BasicBlock *StoreBB = SI.getParent();
12012
12013 // Check to see if the successor block has exactly two incoming edges. If
12014 // so, see if the other predecessor contains a store to the same location.
12015 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012016 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012017
12018 // Determine whether Dest has exactly two predecessors and, if so, compute
12019 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012020 pred_iterator PI = pred_begin(DestBB);
12021 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012022 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012023 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012024 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012025 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012026 return false;
12027
12028 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012029 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012030 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012031 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012032 }
Chris Lattner31755a02007-04-15 01:02:18 +000012033 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012034 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012035
12036 // Bail out if all the relevant blocks aren't distinct (this can happen,
12037 // for example, if SI is in an infinite loop)
12038 if (StoreBB == DestBB || OtherBB == DestBB)
12039 return false;
12040
Chris Lattner31755a02007-04-15 01:02:18 +000012041 // Verify that the other block ends in a branch and is not otherwise empty.
12042 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012043 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012044 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012045 return false;
12046
Chris Lattner31755a02007-04-15 01:02:18 +000012047 // If the other block ends in an unconditional branch, check for the 'if then
12048 // else' case. there is an instruction before the branch.
12049 StoreInst *OtherStore = 0;
12050 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012051 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012052 // Skip over debugging info.
12053 while (isa<DbgInfoIntrinsic>(BBI) ||
12054 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12055 if (BBI==OtherBB->begin())
12056 return false;
12057 --BBI;
12058 }
12059 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012060 OtherStore = dyn_cast<StoreInst>(BBI);
12061 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12062 return false;
12063 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012064 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012065 // destinations is StoreBB, then we have the if/then case.
12066 if (OtherBr->getSuccessor(0) != StoreBB &&
12067 OtherBr->getSuccessor(1) != StoreBB)
12068 return false;
12069
12070 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012071 // if/then triangle. See if there is a store to the same ptr as SI that
12072 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012073 for (;; --BBI) {
12074 // Check to see if we find the matching store.
12075 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12076 if (OtherStore->getOperand(1) != SI.getOperand(1))
12077 return false;
12078 break;
12079 }
Eli Friedman6903a242008-06-13 22:02:12 +000012080 // If we find something that may be using or overwriting the stored
12081 // value, or if we run out of instructions, we can't do the xform.
12082 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012083 BBI == OtherBB->begin())
12084 return false;
12085 }
12086
12087 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012088 // make sure nothing reads or overwrites the stored value in
12089 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012090 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12091 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012092 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012093 return false;
12094 }
12095 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012096
Chris Lattner31755a02007-04-15 01:02:18 +000012097 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012098 Value *MergedVal = OtherStore->getOperand(0);
12099 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012100 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012101 PN->reserveOperandSpace(2);
12102 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012103 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12104 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012105 }
12106
12107 // Advance to a place where it is safe to insert the new store and
12108 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012109 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012110 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12111 OtherStore->isVolatile()), *BBI);
12112
12113 // Nuke the old stores.
12114 EraseInstFromFunction(SI);
12115 EraseInstFromFunction(*OtherStore);
12116 ++NumCombined;
12117 return true;
12118}
12119
Chris Lattner2f503e62005-01-31 05:36:43 +000012120
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012121Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12122 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012123 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012124 BasicBlock *TrueDest;
12125 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012126 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012127 !isa<Constant>(X)) {
12128 // Swap Destinations and condition...
12129 BI.setCondition(X);
12130 BI.setSuccessor(0, FalseDest);
12131 BI.setSuccessor(1, TrueDest);
12132 return &BI;
12133 }
12134
Reid Spencere4d87aa2006-12-23 06:05:41 +000012135 // Cannonicalize fcmp_one -> fcmp_oeq
12136 FCmpInst::Predicate FPred; Value *Y;
12137 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012138 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012139 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12140 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12141 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012142 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012143 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012144 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012145 // Swap Destinations and condition...
12146 BI.setCondition(NewSCC);
12147 BI.setSuccessor(0, FalseDest);
12148 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012149 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012150 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012151 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012152 return &BI;
12153 }
12154
12155 // Cannonicalize icmp_ne -> icmp_eq
12156 ICmpInst::Predicate IPred;
12157 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012158 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012159 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12160 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12161 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12162 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012163 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012164 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012165 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012166 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012167 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012168 BI.setSuccessor(0, FalseDest);
12169 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012170 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012171 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012172 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012173 return &BI;
12174 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012175
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012176 return 0;
12177}
Chris Lattner0864acf2002-11-04 16:18:53 +000012178
Chris Lattner46238a62004-07-03 00:26:11 +000012179Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12180 Value *Cond = SI.getCondition();
12181 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12182 if (I->getOpcode() == Instruction::Add)
12183 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12184 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12185 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012186 SI.setOperand(i,
12187 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012188 AddRHS));
12189 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012190 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012191 return &SI;
12192 }
12193 }
12194 return 0;
12195}
12196
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012197Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012198 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012199
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012200 if (!EV.hasIndices())
12201 return ReplaceInstUsesWith(EV, Agg);
12202
12203 if (Constant *C = dyn_cast<Constant>(Agg)) {
12204 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012205 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012206
12207 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012208 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012209
12210 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12211 // Extract the element indexed by the first index out of the constant
12212 Value *V = C->getOperand(*EV.idx_begin());
12213 if (EV.getNumIndices() > 1)
12214 // Extract the remaining indices out of the constant indexed by the
12215 // first index
12216 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12217 else
12218 return ReplaceInstUsesWith(EV, V);
12219 }
12220 return 0; // Can't handle other constants
12221 }
12222 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12223 // We're extracting from an insertvalue instruction, compare the indices
12224 const unsigned *exti, *exte, *insi, *inse;
12225 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12226 exte = EV.idx_end(), inse = IV->idx_end();
12227 exti != exte && insi != inse;
12228 ++exti, ++insi) {
12229 if (*insi != *exti)
12230 // The insert and extract both reference distinctly different elements.
12231 // This means the extract is not influenced by the insert, and we can
12232 // replace the aggregate operand of the extract with the aggregate
12233 // operand of the insert. i.e., replace
12234 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12235 // %E = extractvalue { i32, { i32 } } %I, 0
12236 // with
12237 // %E = extractvalue { i32, { i32 } } %A, 0
12238 return ExtractValueInst::Create(IV->getAggregateOperand(),
12239 EV.idx_begin(), EV.idx_end());
12240 }
12241 if (exti == exte && insi == inse)
12242 // Both iterators are at the end: Index lists are identical. Replace
12243 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12244 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12245 // with "i32 42"
12246 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12247 if (exti == exte) {
12248 // The extract list is a prefix of the insert list. i.e. replace
12249 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12250 // %E = extractvalue { i32, { i32 } } %I, 1
12251 // with
12252 // %X = extractvalue { i32, { i32 } } %A, 1
12253 // %E = insertvalue { i32 } %X, i32 42, 0
12254 // by switching the order of the insert and extract (though the
12255 // insertvalue should be left in, since it may have other uses).
12256 Value *NewEV = InsertNewInstBefore(
12257 ExtractValueInst::Create(IV->getAggregateOperand(),
12258 EV.idx_begin(), EV.idx_end()),
12259 EV);
12260 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12261 insi, inse);
12262 }
12263 if (insi == inse)
12264 // The insert list is a prefix of the extract list
12265 // We can simply remove the common indices from the extract and make it
12266 // operate on the inserted value instead of the insertvalue result.
12267 // i.e., replace
12268 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12269 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12270 // with
12271 // %E extractvalue { i32 } { i32 42 }, 0
12272 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12273 exti, exte);
12274 }
12275 // Can't simplify extracts from other values. Note that nested extracts are
12276 // already simplified implicitely by the above (extract ( extract (insert) )
12277 // will be translated into extract ( insert ( extract ) ) first and then just
12278 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012279 return 0;
12280}
12281
Chris Lattner220b0cf2006-03-05 00:22:33 +000012282/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12283/// is to leave as a vector operation.
12284static bool CheapToScalarize(Value *V, bool isConstant) {
12285 if (isa<ConstantAggregateZero>(V))
12286 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012287 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012288 if (isConstant) return true;
12289 // If all elts are the same, we can extract.
12290 Constant *Op0 = C->getOperand(0);
12291 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12292 if (C->getOperand(i) != Op0)
12293 return false;
12294 return true;
12295 }
12296 Instruction *I = dyn_cast<Instruction>(V);
12297 if (!I) return false;
12298
12299 // Insert element gets simplified to the inserted element or is deleted if
12300 // this is constant idx extract element and its a constant idx insertelt.
12301 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12302 isa<ConstantInt>(I->getOperand(2)))
12303 return true;
12304 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12305 return true;
12306 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12307 if (BO->hasOneUse() &&
12308 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12309 CheapToScalarize(BO->getOperand(1), isConstant)))
12310 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012311 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12312 if (CI->hasOneUse() &&
12313 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12314 CheapToScalarize(CI->getOperand(1), isConstant)))
12315 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012316
12317 return false;
12318}
12319
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012320/// Read and decode a shufflevector mask.
12321///
12322/// It turns undef elements into values that are larger than the number of
12323/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012324static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12325 unsigned NElts = SVI->getType()->getNumElements();
12326 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12327 return std::vector<unsigned>(NElts, 0);
12328 if (isa<UndefValue>(SVI->getOperand(2)))
12329 return std::vector<unsigned>(NElts, 2*NElts);
12330
12331 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012332 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012333 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12334 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012335 Result.push_back(NElts*2); // undef -> 8
12336 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012337 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012338 return Result;
12339}
12340
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012341/// FindScalarElement - Given a vector and an element number, see if the scalar
12342/// value is already around as a register, for example if it were inserted then
12343/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012344static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012345 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012346 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12347 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012348 unsigned Width = PTy->getNumElements();
12349 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012350 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012351
12352 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012353 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012354 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012356 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012357 return CP->getOperand(EltNo);
12358 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12359 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012360 if (!isa<ConstantInt>(III->getOperand(2)))
12361 return 0;
12362 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012363
12364 // If this is an insert to the element we are looking for, return the
12365 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012366 if (EltNo == IIElt)
12367 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012368
12369 // Otherwise, the insertelement doesn't modify the value, recurse on its
12370 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012371 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012372 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012373 unsigned LHSWidth =
12374 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012375 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012376 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012377 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012378 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012379 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012380 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012381 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012382 }
12383
12384 // Otherwise, we don't know.
12385 return 0;
12386}
12387
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012388Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012389 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012390 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012391 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012392
Dan Gohman07a96762007-07-16 14:29:03 +000012393 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012394 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012395 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012396
Reid Spencer9d6565a2007-02-15 02:26:10 +000012397 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012398 // If vector val is constant with all elements the same, replace EI with
12399 // that element. When the elements are not identical, we cannot replace yet
12400 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012401 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012402 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012403 if (C->getOperand(i) != op0) {
12404 op0 = 0;
12405 break;
12406 }
12407 if (op0)
12408 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012409 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012410
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012411 // If extracting a specified index from the vector, see if we can recursively
12412 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012413 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012414 unsigned IndexVal = IdxC->getZExtValue();
12415 unsigned VectorWidth =
12416 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12417
12418 // If this is extracting an invalid index, turn this into undef, to avoid
12419 // crashing the code below.
12420 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012421 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012422
Chris Lattner867b99f2006-10-05 06:55:50 +000012423 // This instruction only demands the single element from the input vector.
12424 // If the input vector has a single use, simplify it based on this use
12425 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012426 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012427 APInt UndefElts(VectorWidth, 0);
12428 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012429 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012430 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012431 EI.setOperand(0, V);
12432 return &EI;
12433 }
12434 }
12435
Owen Andersond672ecb2009-07-03 00:17:18 +000012436 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012437 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012438
12439 // If the this extractelement is directly using a bitcast from a vector of
12440 // the same number of elements, see if we can find the source element from
12441 // it. In this case, we will end up needing to bitcast the scalars.
12442 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12443 if (const VectorType *VT =
12444 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12445 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012446 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12447 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012448 return new BitCastInst(Elt, EI.getType());
12449 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012450 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012451
Chris Lattner73fa49d2006-05-25 22:53:38 +000012452 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012453 if (I->hasOneUse()) {
12454 // Push extractelement into predecessor operation if legal and
12455 // profitable to do so
12456 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012457 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12458 if (CheapToScalarize(BO, isConstantElt)) {
12459 ExtractElementInst *newEI0 =
12460 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12461 EI.getName()+".lhs");
12462 ExtractElementInst *newEI1 =
12463 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12464 EI.getName()+".rhs");
12465 InsertNewInstBefore(newEI0, EI);
12466 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012467 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012468 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012469 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012470 unsigned AS =
12471 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012472 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012473 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012474 GetElementPtrInst *GEP =
12475 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012476 InsertNewInstBefore(GEP, EI);
12477 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012478 }
12479 }
12480 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12481 // Extracting the inserted element?
12482 if (IE->getOperand(2) == EI.getOperand(1))
12483 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12484 // If the inserted and extracted elements are constants, they must not
12485 // be the same value, extract from the pre-inserted value instead.
12486 if (isa<Constant>(IE->getOperand(2)) &&
12487 isa<Constant>(EI.getOperand(1))) {
12488 AddUsesToWorkList(EI);
12489 EI.setOperand(0, IE->getOperand(0));
12490 return &EI;
12491 }
12492 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12493 // If this is extracting an element from a shufflevector, figure out where
12494 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012495 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12496 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012497 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012498 unsigned LHSWidth =
12499 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12500
12501 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012502 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012503 else if (SrcIdx < LHSWidth*2) {
12504 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012505 Src = SVI->getOperand(1);
12506 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012507 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012508 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012509 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012510 }
12511 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012512 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012513 return 0;
12514}
12515
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012516/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12517/// elements from either LHS or RHS, return the shuffle mask and true.
12518/// Otherwise, return false.
12519static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012520 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012521 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012522 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12523 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012524 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012525
12526 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012527 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012528 return true;
12529 } else if (V == LHS) {
12530 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012531 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012532 return true;
12533 } else if (V == RHS) {
12534 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012535 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012536 return true;
12537 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12538 // If this is an insert of an extract from some other vector, include it.
12539 Value *VecOp = IEI->getOperand(0);
12540 Value *ScalarOp = IEI->getOperand(1);
12541 Value *IdxOp = IEI->getOperand(2);
12542
Chris Lattnerd929f062006-04-27 21:14:21 +000012543 if (!isa<ConstantInt>(IdxOp))
12544 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012545 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012546
12547 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12548 // Okay, we can handle this if the vector we are insertinting into is
12549 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012550 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012551 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012552 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012553 return true;
12554 }
12555 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12556 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012557 EI->getOperand(0)->getType() == V->getType()) {
12558 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012559 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012560
12561 // This must be extracting from either LHS or RHS.
12562 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12563 // Okay, we can handle this if the vector we are insertinting into is
12564 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012565 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012566 // If so, update the mask to reflect the inserted value.
12567 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012568 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012569 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012570 } else {
12571 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012572 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012573 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012574
12575 }
12576 return true;
12577 }
12578 }
12579 }
12580 }
12581 }
12582 // TODO: Handle shufflevector here!
12583
12584 return false;
12585}
12586
12587/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12588/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12589/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012590static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012591 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012592 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012593 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012594 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012595 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012596
12597 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012598 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012599 return V;
12600 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012601 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012602 return V;
12603 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12604 // If this is an insert of an extract from some other vector, include it.
12605 Value *VecOp = IEI->getOperand(0);
12606 Value *ScalarOp = IEI->getOperand(1);
12607 Value *IdxOp = IEI->getOperand(2);
12608
12609 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12610 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12611 EI->getOperand(0)->getType() == V->getType()) {
12612 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012613 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12614 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012615
12616 // Either the extracted from or inserted into vector must be RHSVec,
12617 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012618 if (EI->getOperand(0) == RHS || RHS == 0) {
12619 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012620 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012621 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012622 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012623 return V;
12624 }
12625
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012626 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012627 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12628 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012629 // Everything but the extracted element is replaced with the RHS.
12630 for (unsigned i = 0; i != NumElts; ++i) {
12631 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012632 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012633 }
12634 return V;
12635 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012636
12637 // If this insertelement is a chain that comes from exactly these two
12638 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012639 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12640 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012641 return EI->getOperand(0);
12642
Chris Lattnerefb47352006-04-15 01:39:45 +000012643 }
12644 }
12645 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012646 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012647
12648 // Otherwise, can't do anything fancy. Return an identity vector.
12649 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012650 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012651 return V;
12652}
12653
12654Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12655 Value *VecOp = IE.getOperand(0);
12656 Value *ScalarOp = IE.getOperand(1);
12657 Value *IdxOp = IE.getOperand(2);
12658
Chris Lattner599ded12007-04-09 01:11:16 +000012659 // Inserting an undef or into an undefined place, remove this.
12660 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12661 ReplaceInstUsesWith(IE, VecOp);
12662
Chris Lattnerefb47352006-04-15 01:39:45 +000012663 // If the inserted element was extracted from some other vector, and if the
12664 // indexes are constant, try to turn this into a shufflevector operation.
12665 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12666 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12667 EI->getOperand(0)->getType() == IE.getType()) {
12668 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012669 unsigned ExtractedIdx =
12670 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012671 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012672
12673 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12674 return ReplaceInstUsesWith(IE, VecOp);
12675
12676 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012677 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012678
12679 // If we are extracting a value from a vector, then inserting it right
12680 // back into the same place, just use the input vector.
12681 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12682 return ReplaceInstUsesWith(IE, VecOp);
12683
12684 // We could theoretically do this for ANY input. However, doing so could
12685 // turn chains of insertelement instructions into a chain of shufflevector
12686 // instructions, and right now we do not merge shufflevectors. As such,
12687 // only do this in a situation where it is clear that there is benefit.
12688 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12689 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12690 // the values of VecOp, except then one read from EIOp0.
12691 // Build a new shuffle mask.
12692 std::vector<Constant*> Mask;
12693 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012694 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012695 else {
12696 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012697 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012698 NumVectorElts));
12699 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012700 Mask[InsertedIdx] =
12701 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012702 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012703 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012704 }
12705
12706 // If this insertelement isn't used by some other insertelement, turn it
12707 // (and any insertelements it points to), into one big shuffle.
12708 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12709 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012710 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012711 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12712 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012713 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012714 return new ShuffleVectorInst(LHS, RHS,
12715 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012716 }
12717 }
12718 }
12719
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012720 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12721 APInt UndefElts(VWidth, 0);
12722 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12723 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12724 return &IE;
12725
Chris Lattnerefb47352006-04-15 01:39:45 +000012726 return 0;
12727}
12728
12729
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012730Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12731 Value *LHS = SVI.getOperand(0);
12732 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012733 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012734
12735 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012736
Chris Lattner867b99f2006-10-05 06:55:50 +000012737 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012738 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012739 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012740
Dan Gohman488fbfc2008-09-09 18:11:14 +000012741 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012742
12743 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12744 return 0;
12745
Evan Cheng388df622009-02-03 10:05:09 +000012746 APInt UndefElts(VWidth, 0);
12747 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12748 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012749 LHS = SVI.getOperand(0);
12750 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012751 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012752 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012753
Chris Lattner863bcff2006-05-25 23:48:38 +000012754 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12755 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12756 if (LHS == RHS || isa<UndefValue>(LHS)) {
12757 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012758 // shuffle(undef,undef,mask) -> undef.
12759 return ReplaceInstUsesWith(SVI, LHS);
12760 }
12761
Chris Lattner863bcff2006-05-25 23:48:38 +000012762 // Remap any references to RHS to use LHS.
12763 std::vector<Constant*> Elts;
12764 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012765 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012766 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012767 else {
12768 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012769 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012770 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012771 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012772 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012773 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012774 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012775 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012776 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012777 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012778 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012779 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12780 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012781 LHS = SVI.getOperand(0);
12782 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012783 MadeChange = true;
12784 }
12785
Chris Lattner7b2e27922006-05-26 00:29:06 +000012786 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012787 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012788
Chris Lattner863bcff2006-05-25 23:48:38 +000012789 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12790 if (Mask[i] >= e*2) continue; // Ignore undef values.
12791 // Is this an identity shuffle of the LHS value?
12792 isLHSID &= (Mask[i] == i);
12793
12794 // Is this an identity shuffle of the RHS value?
12795 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012796 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012797
Chris Lattner863bcff2006-05-25 23:48:38 +000012798 // Eliminate identity shuffles.
12799 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12800 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012801
Chris Lattner7b2e27922006-05-26 00:29:06 +000012802 // If the LHS is a shufflevector itself, see if we can combine it with this
12803 // one without producing an unusual shuffle. Here we are really conservative:
12804 // we are absolutely afraid of producing a shuffle mask not in the input
12805 // program, because the code gen may not be smart enough to turn a merged
12806 // shuffle into two specific shuffles: it may produce worse code. As such,
12807 // we only merge two shuffles if the result is one of the two input shuffle
12808 // masks. In this case, merging the shuffles just removes one instruction,
12809 // which we know is safe. This is good for things like turning:
12810 // (splat(splat)) -> splat.
12811 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12812 if (isa<UndefValue>(RHS)) {
12813 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12814
12815 std::vector<unsigned> NewMask;
12816 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12817 if (Mask[i] >= 2*e)
12818 NewMask.push_back(2*e);
12819 else
12820 NewMask.push_back(LHSMask[Mask[i]]);
12821
12822 // If the result mask is equal to the src shuffle or this shuffle mask, do
12823 // the replacement.
12824 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012825 unsigned LHSInNElts =
12826 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012827 std::vector<Constant*> Elts;
12828 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012829 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012830 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012831 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012832 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012833 }
12834 }
12835 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12836 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012837 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012838 }
12839 }
12840 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012841
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012842 return MadeChange ? &SVI : 0;
12843}
12844
12845
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012846
Chris Lattnerea1c4542004-12-08 23:43:58 +000012847
12848/// TryToSinkInstruction - Try to move the specified instruction from its
12849/// current block into the beginning of DestBlock, which can only happen if it's
12850/// safe to move the instruction past all of the instructions between it and the
12851/// end of its block.
12852static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12853 assert(I->hasOneUse() && "Invariants didn't hold!");
12854
Chris Lattner108e9022005-10-27 17:13:11 +000012855 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012856 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012857 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012858
Chris Lattnerea1c4542004-12-08 23:43:58 +000012859 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012860 if (isa<AllocaInst>(I) && I->getParent() ==
12861 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012862 return false;
12863
Chris Lattner96a52a62004-12-09 07:14:34 +000012864 // We can only sink load instructions if there is nothing between the load and
12865 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012866 if (I->mayReadFromMemory()) {
12867 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012868 Scan != E; ++Scan)
12869 if (Scan->mayWriteToMemory())
12870 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012871 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012872
Dan Gohman02dea8b2008-05-23 21:05:58 +000012873 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012874
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012875 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012876 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012877 ++NumSunkInst;
12878 return true;
12879}
12880
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012881
12882/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12883/// all reachable code to the worklist.
12884///
12885/// This has a couple of tricks to make the code faster and more powerful. In
12886/// particular, we constant fold and DCE instructions as we go, to avoid adding
12887/// them to the worklist (this significantly speeds up instcombine on code where
12888/// many instructions are dead or constant). Additionally, if we find a branch
12889/// whose condition is a known constant, we only visit the reachable successors.
12890///
12891static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012892 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012893 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012894 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012895 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012896 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012897
Chris Lattner2c7718a2007-03-23 19:17:18 +000012898 while (!Worklist.empty()) {
12899 BB = Worklist.back();
12900 Worklist.pop_back();
12901
12902 // We have now visited this block! If we've already been here, ignore it.
12903 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012904
12905 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012906 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12907 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012908
Chris Lattner2c7718a2007-03-23 19:17:18 +000012909 // DCE instruction if trivially dead.
12910 if (isInstructionTriviallyDead(Inst)) {
12911 ++NumDeadInst;
12912 DOUT << "IC: DCE: " << *Inst;
12913 Inst->eraseFromParent();
12914 continue;
12915 }
12916
12917 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012918 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012919 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12920 Inst->replaceAllUsesWith(C);
12921 ++NumConstProp;
12922 Inst->eraseFromParent();
12923 continue;
12924 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012925
Devang Patel7fe1dec2008-11-19 18:56:50 +000012926 // If there are two consecutive llvm.dbg.stoppoint calls then
12927 // it is likely that the optimizer deleted code in between these
12928 // two intrinsics.
12929 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12930 if (DBI_Next) {
12931 if (DBI_Prev
12932 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12933 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12934 IC.RemoveFromWorkList(DBI_Prev);
12935 DBI_Prev->eraseFromParent();
12936 }
12937 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012938 } else {
12939 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012940 }
12941
Chris Lattner2c7718a2007-03-23 19:17:18 +000012942 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012943 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012944
12945 // Recursively visit successors. If this is a branch or switch on a
12946 // constant, only visit the reachable successor.
12947 TerminatorInst *TI = BB->getTerminator();
12948 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12949 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12950 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012951 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012952 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012953 continue;
12954 }
12955 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12956 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12957 // See if this is an explicit destination.
12958 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12959 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012960 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012961 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012962 continue;
12963 }
12964
12965 // Otherwise it is the default destination.
12966 Worklist.push_back(SI->getSuccessor(0));
12967 continue;
12968 }
12969 }
12970
12971 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12972 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012973 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012974}
12975
Chris Lattnerec9c3582007-03-03 02:04:50 +000012976bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012977 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012978 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012979
12980 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12981 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012982
Chris Lattnerb3d59702005-07-07 20:40:38 +000012983 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012984 // Do a depth-first traversal of the function, populate the worklist with
12985 // the reachable instructions. Ignore blocks that are not reachable. Keep
12986 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012987 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012988 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012989
Chris Lattnerb3d59702005-07-07 20:40:38 +000012990 // Do a quick scan over the function. If we find any blocks that are
12991 // unreachable, remove any instructions inside of them. This prevents
12992 // the instcombine code from having to deal with some bad special cases.
12993 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12994 if (!Visited.count(BB)) {
12995 Instruction *Term = BB->getTerminator();
12996 while (Term != BB->begin()) { // Remove instrs bottom-up
12997 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012998
Bill Wendlingb7427032006-11-26 09:46:52 +000012999 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000013000 // A debug intrinsic shouldn't force another iteration if we weren't
13001 // going to do one without it.
13002 if (!isa<DbgInfoIntrinsic>(I)) {
13003 ++NumDeadInst;
13004 Changed = true;
13005 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000013006 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000013007 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013008 I->eraseFromParent();
13009 }
13010 }
13011 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013012
Chris Lattnerdbab3862007-03-02 21:28:56 +000013013 while (!Worklist.empty()) {
13014 Instruction *I = RemoveOneFromWorkList();
13015 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013016
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013017 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013018 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013019 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000013020 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013021 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013022 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013023
Bill Wendlingb7427032006-11-26 09:46:52 +000013024 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013025
13026 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013027 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013028 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013029 continue;
13030 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013031
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013032 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013033 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013034 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013035
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013036 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013037 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013038 ReplaceInstUsesWith(*I, C);
13039
Chris Lattner62b14df2002-09-02 04:59:56 +000013040 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013041 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013042 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013043 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013044 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013045 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013046
Dan Gohman31e4c772009-05-07 19:43:39 +000013047 if (TD &&
13048 (I->getType()->getTypeID() == Type::VoidTyID ||
13049 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013050 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013051 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013053 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13054 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013055 if (NewC != CE) {
13056 i->set(NewC);
13057 Changed = true;
13058 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013059 }
13060
Chris Lattnerea1c4542004-12-08 23:43:58 +000013061 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013062 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013063 BasicBlock *BB = I->getParent();
13064 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13065 if (UserParent != BB) {
13066 bool UserIsSuccessor = false;
13067 // See if the user is one of our successors.
13068 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13069 if (*SI == UserParent) {
13070 UserIsSuccessor = true;
13071 break;
13072 }
13073
13074 // If the user is one of our immediate successors, and if that successor
13075 // only has us as a predecessors (we'd have to split the critical edge
13076 // otherwise), we can keep going.
13077 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13078 next(pred_begin(UserParent)) == pred_end(UserParent))
13079 // Okay, the CFG is simple enough, try to sink this instruction.
13080 Changed |= TryToSinkInstruction(I, UserParent);
13081 }
13082 }
13083
Chris Lattner8a2a3112001-12-14 16:52:21 +000013084 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013085#ifndef NDEBUG
13086 std::string OrigI;
13087#endif
13088 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013089 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013090 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013091 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013092 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013093 DOUT << "IC: Old = " << *I
13094 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013095
Chris Lattnerf523d062004-06-09 05:08:07 +000013096 // Everything uses the new instruction now.
13097 I->replaceAllUsesWith(Result);
13098
13099 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013100 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013101 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013102
Chris Lattner6934a042007-02-11 01:23:03 +000013103 // Move the name to the new instruction first.
13104 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013105
13106 // Insert the new instruction into the basic block...
13107 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013108 BasicBlock::iterator InsertPos = I;
13109
13110 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13111 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13112 ++InsertPos;
13113
13114 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013115
Chris Lattner00d51312004-05-01 23:27:23 +000013116 // Make sure that we reprocess all operands now that we reduced their
13117 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013118 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013119
Chris Lattnerf523d062004-06-09 05:08:07 +000013120 // Instructions can end up on the worklist more than once. Make sure
13121 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013122 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013123
13124 // Erase the old instruction.
13125 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013126 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013127#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013128 DOUT << "IC: Mod = " << OrigI
13129 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013130#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013131
Chris Lattner90ac28c2002-08-02 19:29:35 +000013132 // If the instruction was modified, it's possible that it is now dead.
13133 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013134 if (isInstructionTriviallyDead(I)) {
13135 // Make sure we process all operands now that we are reducing their
13136 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013137 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013138
Chris Lattner00d51312004-05-01 23:27:23 +000013139 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013140 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013141 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013142 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013143 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013144 AddToWorkList(I);
13145 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013146 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013147 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013148 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013149 }
13150 }
13151
Chris Lattnerec9c3582007-03-03 02:04:50 +000013152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013153
13154 // Do an explicit clear, this shrinks the map if needed.
13155 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013156 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013157}
13158
Chris Lattnerec9c3582007-03-03 02:04:50 +000013159
13160bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013161 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13162
Chris Lattnerec9c3582007-03-03 02:04:50 +000013163 bool EverMadeChange = false;
13164
13165 // Iterate while there is work to do.
13166 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013167 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013168 EverMadeChange = true;
13169 return EverMadeChange;
13170}
13171
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013172FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013173 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013174}