blob: 89b4c6569be05e113060ece805d5e989e73d2dda [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"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000052#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000053#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000054#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000055#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000056#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000057#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000058#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000059#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000060#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000061#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000062#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000063#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000064using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000065using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000066
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumCombined , "Number of insts combined");
68STATISTIC(NumConstProp, "Number of constant folds");
69STATISTIC(NumDeadInst , "Number of dead inst eliminated");
70STATISTIC(NumDeadStore, "Number of dead stores eliminated");
71STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000072
Chris Lattner0e5f4992006-12-19 21:40:18 +000073namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000074 class VISIBILITY_HIDDEN InstCombiner
75 : public FunctionPass,
76 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000077 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000078 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000080 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000081 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000083 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000084 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000085
Owen Anderson07cf79e2009-07-06 23:00:19 +000086 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000087
Chris Lattnerdbab3862007-03-02 21:28:56 +000088 /// AddToWorkList - Add the specified instruction to the worklist if it
89 /// isn't already in it.
90 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000091 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000092 Worklist.push_back(I);
93 }
94
95 // RemoveFromWorkList - remove I from the worklist if it exists.
96 void RemoveFromWorkList(Instruction *I) {
97 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
98 if (It == WorklistMap.end()) return; // Not in worklist.
99
100 // Don't bother moving everything down, just null out the slot.
101 Worklist[It->second] = 0;
102
103 WorklistMap.erase(It);
104 }
105
106 Instruction *RemoveOneFromWorkList() {
107 Instruction *I = Worklist.back();
108 Worklist.pop_back();
109 WorklistMap.erase(I);
110 return I;
111 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000112
Chris Lattnerdbab3862007-03-02 21:28:56 +0000113
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000114 /// AddUsersToWorkList - When an instruction is simplified, add all users of
115 /// the instruction to the work lists because they might get more simplified
116 /// now.
117 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000118 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000119 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000120 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000121 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000122 }
123
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000124 /// AddUsesToWorkList - When an instruction is simplified, add operands to
125 /// the work lists because they might get more simplified now.
126 ///
127 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000128 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
129 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000130 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000131 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000132
133 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
134 /// dead. Add all of its operands to the worklist, turning them into
135 /// undef's to reduce the number of uses of those instructions.
136 ///
137 /// Return the specified operand before it is turned into an undef.
138 ///
139 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
140 Value *R = I.getOperand(op);
141
Gabor Greif177dd3f2008-06-12 21:37:33 +0000142 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
143 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000144 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000145 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000146 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000147 }
148
149 return R;
150 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000151
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000153 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000154
155 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000158 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000159 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000160 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000161 }
162
Chris Lattner28977af2004-04-05 01:30:19 +0000163 TargetData &getTargetData() const { return *TD; }
164
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // Visitation implementation - Implement instruction combining for different
166 // instruction types. The semantics are as follows:
167 // Return Value:
168 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000169 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000170 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000171 //
Chris Lattner7e708292002-06-25 16:13:24 +0000172 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000173 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000178 Instruction *visitURem(BinaryOperator &I);
179 Instruction *visitSRem(BinaryOperator &I);
180 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000181 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000182 Instruction *commonRemTransforms(BinaryOperator &I);
183 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000184 Instruction *commonDivTransforms(BinaryOperator &I);
185 Instruction *commonIDivTransforms(BinaryOperator &I);
186 Instruction *visitUDiv(BinaryOperator &I);
187 Instruction *visitSDiv(BinaryOperator &I);
188 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000189 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000190 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000191 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000192 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000193 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000194 Instruction *visitOr (BinaryOperator &I);
195 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000196 Instruction *visitShl(BinaryOperator &I);
197 Instruction *visitAShr(BinaryOperator &I);
198 Instruction *visitLShr(BinaryOperator &I);
199 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000200 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
201 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000202 Instruction *visitFCmpInst(FCmpInst &I);
203 Instruction *visitICmpInst(ICmpInst &I);
204 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000205 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
206 Instruction *LHS,
207 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000208 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
209 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000210
Reid Spencere4d87aa2006-12-23 06:05:41 +0000211 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
212 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000213 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000214 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000215 Instruction *commonCastTransforms(CastInst &CI);
216 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000218 Instruction *visitTrunc(TruncInst &CI);
219 Instruction *visitZExt(ZExtInst &CI);
220 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000221 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000222 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000223 Instruction *visitFPToUI(FPToUIInst &FI);
224 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000225 Instruction *visitUIToFP(CastInst &CI);
226 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000227 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000228 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000229 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000230 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
231 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000232 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000233 Instruction *visitSelectInst(SelectInst &SI);
234 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 Instruction *visitCallInst(CallInst &CI);
236 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000237 Instruction *visitPHINode(PHINode &PN);
238 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000239 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000240 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000241 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000242 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000243 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000244 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000245 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000246 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000247 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000248 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000249
250 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000251 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000252
Chris Lattner9fe38862003-06-19 17:00:31 +0000253 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000254 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000255 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000256 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000257 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
258 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000259 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000260 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
261
Chris Lattner9fe38862003-06-19 17:00:31 +0000262
Chris Lattner28977af2004-04-05 01:30:19 +0000263 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000264 // InsertNewInstBefore - insert an instruction New before instruction Old
265 // in the program. Add the new instruction to the worklist.
266 //
Chris Lattner955f3312004-09-28 21:48:02 +0000267 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000268 assert(New && New->getParent() == 0 &&
269 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000270 BasicBlock *BB = Old.getParent();
271 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000272 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000273 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000274 }
275
Chris Lattner0c967662004-09-24 15:21:34 +0000276 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
277 /// This also adds the cast to the worklist. Finally, this returns the
278 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000279 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
280 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000281 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000282
Chris Lattnere2ed0572006-04-06 19:19:17 +0000283 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000284 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000285
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000286 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000287 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000288 return C;
289 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000290
291 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
292 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
293 }
294
Chris Lattner0c967662004-09-24 15:21:34 +0000295
Chris Lattner8b170942002-08-09 23:47:40 +0000296 // ReplaceInstUsesWith - This method is to be used when an instruction is
297 // found to be dead, replacable with another preexisting expression. Here
298 // we add all uses of I to the worklist, replace all uses of I with the new
299 // value, then return I, so that the inst combiner will know that I was
300 // modified.
301 //
302 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000303 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000304 if (&I != V) {
305 I.replaceAllUsesWith(V);
306 return &I;
307 } else {
308 // If we are replacing the instruction with itself, this must be in a
309 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000310 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000311 return &I;
312 }
Chris Lattner8b170942002-08-09 23:47:40 +0000313 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000314
315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000322 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000323 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324 return 0; // Don't do anything with FI
325 }
Chris Lattner173234a2008-06-02 01:18:21 +0000326
327 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
328 APInt &KnownOne, unsigned Depth = 0) const {
329 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
330 }
331
332 bool MaskedValueIsZero(Value *V, const APInt &Mask,
333 unsigned Depth = 0) const {
334 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
335 }
336 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
337 return llvm::ComputeNumSignBits(Op, TD, Depth);
338 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000339
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000340 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000341
Reid Spencere4d87aa2006-12-23 06:05:41 +0000342 /// SimplifyCommutative - This performs a few simplifications for
343 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000344 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000345
Reid Spencere4d87aa2006-12-23 06:05:41 +0000346 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
347 /// most-complex to least-complex order.
348 bool SimplifyCompare(CmpInst &I);
349
Chris Lattner886ab6c2009-01-31 08:15:18 +0000350 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
351 /// based on the demanded bits.
352 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
353 APInt& KnownZero, APInt& KnownOne,
354 unsigned Depth);
355 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000356 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000357 unsigned Depth=0);
358
359 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
360 /// SimplifyDemandedBits knows about. See if the instruction has any
361 /// properties that allow us to simplify its operands.
362 bool SimplifyDemandedInstructionBits(Instruction &Inst);
363
Evan Cheng388df622009-02-03 10:05:09 +0000364 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
365 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000366
Chris Lattner4e998b22004-09-29 05:07:12 +0000367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
371
Chris Lattnerbac32862004-11-14 19:13:23 +0000372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000377 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
Chris Lattner7da52b22006-11-01 04:51:18 +0000379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000382
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000388 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393
Reid Spencerc55b2432006-12-13 18:21:21 +0000394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395
Dan Gohman6de29f82009-06-15 22:12:54 +0000396 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000397 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000400
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000401 };
402}
403
Dan Gohman844731a2008-05-13 00:00:25 +0000404char InstCombiner::ID = 0;
405static RegisterPass<InstCombiner>
406X("instcombine", "Combine redundant instructions");
407
Chris Lattner4f98c562003-03-10 21:43:22 +0000408// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000409// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000410static unsigned getComplexity(Value *V) {
411 if (isa<Instruction>(V)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000412 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
413 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 return 3;
415 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000420
Chris Lattnerc8802d22003-03-11 00:12:48 +0000421// isOnlyUse - Return true if this instruction will be deleted if we stop using
422// it.
423static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000424 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000425}
426
Chris Lattner4cb170c2004-02-23 06:38:22 +0000427// getPromotedType - Return the specified type promoted as it would be to pass
428// though a va_arg area...
429static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000433 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000434 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000435}
436
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000437/// getBitCastOperand - If the specified operand is a CastInst, a constant
438/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000440static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000443 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000444 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445 // GetElementPtrInst?
446 if (GEP->hasAllZeroIndices())
447 return GEP->getOperand(0);
448 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000450 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000451 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000452 else if (CE->getOpcode() == Instruction::GetElementPtr) {
453 // GetElementPtr ConstantExp?
454 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
455 I != E; ++I) {
456 ConstantInt *CI = dyn_cast<ConstantInt>(I);
457 if (!CI || !CI->isZero())
458 // Any non-zero indices? Not cast-like.
459 return 0;
460 }
461 // All-zero indices? This is just like casting.
462 return CE->getOperand(0);
463 }
464 }
Chris Lattnereed48272005-09-13 00:40:14 +0000465 return 0;
466}
467
Reid Spencer3da59db2006-11-27 01:05:10 +0000468/// This function is a wrapper around CastInst::isEliminableCastPair. It
469/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000470static Instruction::CastOps
471isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
476) {
477
478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000480
Reid Spencer3da59db2006-11-27 01:05:10 +0000481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000484
Chris Lattnera0e69692009-03-24 18:35:40 +0000485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486 DstTy, TD->getIntPtrType());
487
488 // We don't want to form an inttoptr or ptrtoint that converts to an integer
489 // type that differs from the pointer size.
490 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
491 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
492 Res = 0;
493
494 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000495}
496
497/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
498/// in any code being generated. It does not require codegen if V is simple
499/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000500static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
501 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000502 if (V->getType() == Ty || isa<Constant>(V)) return false;
503
Chris Lattner01575b72006-05-25 23:24:33 +0000504 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000505 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000506 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000507 return false;
508 return true;
509}
510
Chris Lattner4f98c562003-03-10 21:43:22 +0000511// SimplifyCommutative - This performs a few simplifications for commutative
512// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000513//
Chris Lattner4f98c562003-03-10 21:43:22 +0000514// 1. Order operands such that they are listed from right (least complex) to
515// left (most complex). This puts constants before unary operators before
516// binary operators.
517//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
519// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000520//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000522 bool Changed = false;
523 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000525
Chris Lattner4f98c562003-03-10 21:43:22 +0000526 if (!I.isAssociative()) return Changed;
527 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000528 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
529 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
530 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000531 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000532 cast<Constant>(I.getOperand(1)),
533 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 I.setOperand(0, Op->getOperand(0));
535 I.setOperand(1, Folded);
536 return true;
537 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
538 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
539 isOnlyUse(Op) && isOnlyUse(Op1)) {
540 Constant *C1 = cast<Constant>(Op->getOperand(1));
541 Constant *C2 = cast<Constant>(Op1->getOperand(1));
542
543 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000544 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000545 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 Op1->getOperand(0),
547 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000548 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549 I.setOperand(0, New);
550 I.setOperand(1, Folded);
551 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000552 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000555}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000556
Reid Spencere4d87aa2006-12-23 06:05:41 +0000557/// SimplifyCompare - For a CmpInst this function just orders the operands
558/// so that theyare listed from right (least complex) to left (most complex).
559/// This puts constants before unary operators before binary operators.
560bool InstCombiner::SimplifyCompare(CmpInst &I) {
561 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
562 return false;
563 I.swapOperands();
564 // Compare instructions are not associative so there's nothing else we can do.
565 return true;
566}
567
Chris Lattner8d969642003-03-10 23:06:50 +0000568// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
569// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000570//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000571static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000572 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000573 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000574
Chris Lattner0ce85802004-12-14 20:08:06 +0000575 // Constants can be considered to be negated values if they can be folded.
576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000577 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000578
579 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000581 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000582
Chris Lattner8d969642003-03-10 23:06:50 +0000583 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000584}
585
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000586// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
587// instruction if the LHS is a constant negative zero (which is the 'negate'
588// form).
589//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000590static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000591 if (BinaryOperator::isFNeg(V))
592 return BinaryOperator::getFNegArgument(V);
593
594 // Constants can be considered to be negated values if they can be folded.
595 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000596 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000597
598 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
599 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000600 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000601
602 return 0;
603}
604
Owen Anderson07cf79e2009-07-06 23:00:19 +0000605static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000606 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000607 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000608
609 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000610 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000611 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000612 return 0;
613}
614
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615// dyn_castFoldableMul - If this value is a multiply that can be folded into
616// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000617// non-constant operand of the multiply, and set CST to point to the multiplier.
618// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619//
Owen Andersond672ecb2009-07-03 00:17:18 +0000620static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000621 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000622 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000625 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000627 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000628 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000630 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000631 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000632 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000633 return I->getOperand(0);
634 }
635 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000636 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000637}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000638
Chris Lattner574da9b2005-01-13 20:14:25 +0000639/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
640/// expression, return it.
641static User *dyn_castGetElementPtr(Value *V) {
642 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
643 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
644 if (CE->getOpcode() == Instruction::GetElementPtr)
645 return cast<User>(V);
646 return false;
647}
648
Dan Gohmaneee962e2008-04-10 18:43:06 +0000649/// getOpcode - If this is an Instruction or a ConstantExpr, return the
650/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000651static unsigned getOpcode(const Value *V) {
652 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000653 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000654 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000655 return CE->getOpcode();
656 // Use UserOp1 to mean there's no opcode.
657 return Instruction::UserOp1;
658}
659
Reid Spencer7177c3a2007-03-25 05:33:51 +0000660/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000661static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000662 return Context->getConstantExprAdd(C,
663 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000664}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000665/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000666static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000667 return Context->getConstantExprSub(C,
668 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000669}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000670/// MultiplyOverflows - True if the multiply can not be expressed in an int
671/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000672static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000673 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000674 uint32_t W = C1->getBitWidth();
675 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
676 if (sign) {
677 LHSExt.sext(W * 2);
678 RHSExt.sext(W * 2);
679 } else {
680 LHSExt.zext(W * 2);
681 RHSExt.zext(W * 2);
682 }
683
684 APInt MulExt = LHSExt * RHSExt;
685
686 if (sign) {
687 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
688 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
689 return MulExt.slt(Min) || MulExt.sgt(Max);
690 } else
691 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
692}
Chris Lattner955f3312004-09-28 21:48:02 +0000693
Reid Spencere7816b52007-03-08 01:52:58 +0000694
Chris Lattner255d8912006-02-11 09:31:47 +0000695/// ShrinkDemandedConstant - Check to see if the specified operand of the
696/// specified instruction is a constant integer. If so, check to see if there
697/// are any bits set in the constant that are not demanded. If so, shrink the
698/// constant and return true.
699static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000700 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000701 assert(I && "No instruction?");
702 assert(OpNo < I->getNumOperands() && "Operand index too large");
703
704 // If the operand is not a constant integer, nothing to do.
705 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
706 if (!OpC) return false;
707
708 // If there are no bits set that aren't demanded, nothing to do.
709 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
710 if ((~Demanded & OpC->getValue()) == 0)
711 return false;
712
713 // This instruction is producing bits that are not demanded. Shrink the RHS.
714 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000715 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000716 return true;
717}
718
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
720// set of known zero and one bits, compute the maximum and minimum values that
721// could have the specified known zero and known one bits, returning them in
722// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000723static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000724 const APInt& KnownOne,
725 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000726 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
727 KnownZero.getBitWidth() == Min.getBitWidth() &&
728 KnownZero.getBitWidth() == Max.getBitWidth() &&
729 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000730 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
733 // bit if it is unknown.
734 Min = KnownOne;
735 Max = KnownOne|UnknownBits;
736
Dan Gohman1c8491e2009-04-25 17:12:48 +0000737 if (UnknownBits.isNegative()) { // Sign bit is unknown
738 Min.set(Min.getBitWidth()-1);
739 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741}
742
743// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
744// a set of known zero and one bits, compute the maximum and minimum values that
745// could have the specified known zero and known one bits, returning them in
746// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000747static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000748 const APInt &KnownOne,
749 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000750 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
751 KnownZero.getBitWidth() == Min.getBitWidth() &&
752 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000753 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000754 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000755
756 // The minimum value is when the unknown bits are all zeros.
757 Min = KnownOne;
758 // The maximum value is when the unknown bits are all ones.
759 Max = KnownOne|UnknownBits;
760}
Chris Lattner255d8912006-02-11 09:31:47 +0000761
Chris Lattner886ab6c2009-01-31 08:15:18 +0000762/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
763/// SimplifyDemandedBits knows about. See if the instruction has any
764/// properties that allow us to simplify its operands.
765bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000766 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000767 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
768 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
769
770 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
771 KnownZero, KnownOne, 0);
772 if (V == 0) return false;
773 if (V == &Inst) return true;
774 ReplaceInstUsesWith(Inst, V);
775 return true;
776}
777
778/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
779/// specified instruction operand if possible, updating it in place. It returns
780/// true if it made any change and false otherwise.
781bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
782 APInt &KnownZero, APInt &KnownOne,
783 unsigned Depth) {
784 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
785 KnownZero, KnownOne, Depth);
786 if (NewVal == 0) return false;
787 U.set(NewVal);
788 return true;
789}
790
791
792/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
793/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000794/// that only the bits set in DemandedMask of the result of V are ever used
795/// downstream. Consequently, depending on the mask and V, it may be possible
796/// to replace V with a constant or one of its operands. In such cases, this
797/// function does the replacement and returns true. In all other cases, it
798/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000799/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000800/// to be zero in the expression. These are provided to potentially allow the
801/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
802/// the expression. KnownOne and KnownZero always follow the invariant that
803/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
804/// the bits in KnownOne and KnownZero may only be accurate for those bits set
805/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
806/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000807///
808/// This returns null if it did not change anything and it permits no
809/// simplification. This returns V itself if it did some simplification of V's
810/// operands based on the information about what bits are demanded. This returns
811/// some other non-null value if it found out that V is equal to another value
812/// in the context where the specified bits are demanded, but not for all users.
813Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
815 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000816 assert(V != 0 && "Null pointer of Value???");
817 assert(Depth <= 6 && "Limit Search Depth");
818 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000819 const Type *VTy = V->getType();
820 assert((TD || !isa<PointerType>(VTy)) &&
821 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000822 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
823 (!VTy->isIntOrIntVector() ||
824 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000825 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000826 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000827 "Value *V, DemandedMask, KnownZero and KnownOne "
828 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
830 // We know all of the bits for a constant!
831 KnownOne = CI->getValue() & DemandedMask;
832 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000833 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000835 if (isa<ConstantPointerNull>(V)) {
836 // We know all of the bits for a constant!
837 KnownOne.clear();
838 KnownZero = DemandedMask;
839 return 0;
840 }
841
Chris Lattner08d2cc72009-01-31 07:26:06 +0000842 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000843 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000844 if (DemandedMask == 0) { // Not demanding any bits from V.
845 if (isa<UndefValue>(V))
846 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000847 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000848 }
849
Chris Lattner4598c942009-01-31 08:24:16 +0000850 if (Depth == 6) // Limit search depth.
851 return 0;
852
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000853 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
854 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
855
Dan Gohman1c8491e2009-04-25 17:12:48 +0000856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) {
858 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
859 return 0; // Only analyze instructions.
860 }
861
Chris Lattner4598c942009-01-31 08:24:16 +0000862 // If there are multiple uses of this value and we aren't at the root, then
863 // we can't do any simplifications of the operands, because DemandedMask
864 // only reflects the bits demanded by *one* of the users.
865 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000866 // Despite the fact that we can't simplify this instruction in all User's
867 // context, we can at least compute the knownzero/knownone bits, and we can
868 // do simplifications that apply to *just* the one user if we know that
869 // this instruction has a simpler value in that context.
870 if (I->getOpcode() == Instruction::And) {
871 // If either the LHS or the RHS are Zero, the result is zero.
872 ComputeMaskedBits(I->getOperand(1), DemandedMask,
873 RHSKnownZero, RHSKnownOne, Depth+1);
874 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
875 LHSKnownZero, LHSKnownOne, Depth+1);
876
877 // If all of the demanded bits are known 1 on one side, return the other.
878 // These bits cannot contribute to the result of the 'and' in this
879 // context.
880 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
881 (DemandedMask & ~LHSKnownZero))
882 return I->getOperand(0);
883 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
884 (DemandedMask & ~RHSKnownZero))
885 return I->getOperand(1);
886
887 // If all of the demanded bits in the inputs are known zeros, return zero.
888 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000889 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000890
891 } else if (I->getOpcode() == Instruction::Or) {
892 // We can simplify (X|Y) -> X or Y in the user's context if we know that
893 // only bits from X or Y are demanded.
894
895 // If either the LHS or the RHS are One, the result is One.
896 ComputeMaskedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1);
898 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
899 LHSKnownZero, LHSKnownOne, Depth+1);
900
901 // If all of the demanded bits are known zero on one side, return the
902 // other. These bits cannot contribute to the result of the 'or' in this
903 // context.
904 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
905 (DemandedMask & ~LHSKnownOne))
906 return I->getOperand(0);
907 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
908 (DemandedMask & ~RHSKnownOne))
909 return I->getOperand(1);
910
911 // If all of the potentially set bits on one side are known to be set on
912 // the other side, just use the 'other' side.
913 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
914 (DemandedMask & (~RHSKnownZero)))
915 return I->getOperand(0);
916 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
917 (DemandedMask & (~LHSKnownZero)))
918 return I->getOperand(1);
919 }
920
Chris Lattner4598c942009-01-31 08:24:16 +0000921 // Compute the KnownZero/KnownOne bits to simplify things downstream.
922 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
923 return 0;
924 }
925
926 // If this is the root being simplified, allow it to have multiple uses,
927 // just set the DemandedMask to all bits so that we can try to simplify the
928 // operands. This allows visitTruncInst (for example) to simplify the
929 // operand of a trunc without duplicating all the logic below.
930 if (Depth == 0 && !V->hasOneUse())
931 DemandedMask = APInt::getAllOnesValue(BitWidth);
932
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000934 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 case Instruction::And:
938 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
940 RHSKnownZero, RHSKnownOne, Depth+1) ||
941 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 return I;
944 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
945 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000946
947 // If all of the demanded bits are known 1 on one side, return the other.
948 // These bits cannot contribute to the result of the 'and'.
949 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
950 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000951 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000952 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
953 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955
956 // If all of the demanded bits in the inputs are known zeros, return zero.
957 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000958 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000961 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000963
964 // Output known-1 bits are only known if set in both the LHS & RHS.
965 RHSKnownOne &= LHSKnownOne;
966 // Output known-0 are known to be clear if zero in either the LHS | RHS.
967 RHSKnownZero |= LHSKnownZero;
968 break;
969 case Instruction::Or:
970 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I;
976 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
977 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000978
979 // If all of the demanded bits are known zero on one side, return the other.
980 // These bits cannot contribute to the result of the 'or'.
981 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
982 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
985 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987
988 // If all of the potentially set bits on one side are known to be set on
989 // the other side, just use the 'other' side.
990 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
991 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000993 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
994 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000996
997 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000998 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // Output known-0 bits are only known if clear in both the LHS & RHS.
1002 RHSKnownZero &= LHSKnownZero;
1003 // Output known-1 are known to be set if set in either the LHS | RHS.
1004 RHSKnownOne |= LHSKnownOne;
1005 break;
1006 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1) ||
1009 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001010 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I;
1012 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1013 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001014
1015 // If all of the demanded bits are known zero on one side, return the other.
1016 // These bits cannot contribute to the result of the 'xor'.
1017 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
1022 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1023 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1024 (RHSKnownOne & LHSKnownOne);
1025 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1026 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1027 (RHSKnownOne & LHSKnownZero);
1028
1029 // If all of the demanded bits are known to be zero on one side or the
1030 // other, turn this into an *inclusive* or.
1031 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1032 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1033 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001034 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 }
1038
1039 // If all of the demanded bits on one side are known, and all of the set
1040 // bits on that side are also known to be set on the other side, turn this
1041 // into an AND, as we know the bits will be cleared.
1042 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1043 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1044 // all known
1045 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001046 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001047 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001048 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001050 }
1051 }
1052
1053 // If the RHS is a constant, see if we can simplify it.
1054 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001055 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057
1058 RHSKnownZero = KnownZeroOut;
1059 RHSKnownOne = KnownOneOut;
1060 break;
1061 }
1062 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001063 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1) ||
1065 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I;
1068 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1069 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001072 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1073 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001075
1076 // Only known if known in both the LHS and RHS.
1077 RHSKnownOne &= LHSKnownOne;
1078 RHSKnownZero &= LHSKnownZero;
1079 break;
1080 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001081 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001082 DemandedMask.zext(truncBf);
1083 RHSKnownZero.zext(truncBf);
1084 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001087 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001088 DemandedMask.trunc(BitWidth);
1089 RHSKnownZero.trunc(BitWidth);
1090 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 break;
1093 }
1094 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001095 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001097
1098 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1099 if (const VectorType *SrcVTy =
1100 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1101 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1102 // Don't touch a bitcast between vectors of different element counts.
1103 return false;
1104 } else
1105 // Don't touch a scalar-to-vector bitcast.
1106 return false;
1107 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1108 // Don't touch a vector-to-scalar bitcast.
1109 return false;
1110
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001113 return I;
1114 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 break;
1116 case Instruction::ZExt: {
1117 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001118 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
Zhou Shengd48653a2007-03-29 04:45:55 +00001120 DemandedMask.trunc(SrcBitWidth);
1121 RHSKnownZero.trunc(SrcBitWidth);
1122 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001125 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 DemandedMask.zext(BitWidth);
1127 RHSKnownZero.zext(BitWidth);
1128 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 break;
1133 }
1134 case Instruction::SExt: {
1135 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001136 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
Reid Spencer8cb68342007-03-12 17:25:59 +00001138 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001139 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001140
Zhou Sheng01542f32007-03-29 02:26:30 +00001141 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 // If any of the sign extended bits are demanded, we know that the sign
1143 // bit is demanded.
1144 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001145 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001146
Zhou Shengd48653a2007-03-29 04:45:55 +00001147 InputDemandedBits.trunc(SrcBitWidth);
1148 RHSKnownZero.trunc(SrcBitWidth);
1149 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001151 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001152 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001153 InputDemandedBits.zext(BitWidth);
1154 RHSKnownZero.zext(BitWidth);
1155 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001157
1158 // If the sign bit of the input is known set or clear, then we know the
1159 // top bits of the result.
1160
1161 // If the input sign bit is known zero, or if the NewBits are not demanded
1162 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1166 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001167 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001168 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 }
1170 break;
1171 }
1172 case Instruction::Add: {
1173 // Figure out what the input bits are. If the top bits of the and result
1174 // are not demanded, then the add doesn't demand them from its input
1175 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001177
1178 // If there is a constant on the RHS, there are a variety of xformations
1179 // we can do.
1180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181 // If null, this should be simplified elsewhere. Some of the xforms here
1182 // won't work if the RHS is zero.
1183 if (RHS->isZero())
1184 break;
1185
1186 // If the top bit of the output is demanded, demand everything from the
1187 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001189
1190 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001193 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
1195 // If the RHS of the add has bits set that can't affect the input, reduce
1196 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001197 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001199
1200 // Avoid excess work.
1201 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1202 break;
1203
1204 // Turn it into OR if input bits are zero.
1205 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1206 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001207 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001208 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 }
1211
1212 // We can say something about the output known-zero and known-one bits,
1213 // depending on potential carries from the input constant and the
1214 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1215 // bits set and the RHS constant is 0x01001, then we know we have a known
1216 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1217
1218 // To compute this, we first compute the potential carry bits. These are
1219 // the bits which may be modified. I'm not aware of a better way to do
1220 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001221 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001222 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001223
1224 // Now that we know which bits have carries, compute the known-1/0 sets.
1225
1226 // Bits are known one if they are known zero in one operand and one in the
1227 // other, and there is no input carry.
1228 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1229 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1230
1231 // Bits are known zero if they are known zero in both operands and there
1232 // is no input carry.
1233 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1234 } else {
1235 // If the high-bits of this ADD are not demanded, then it does not demand
1236 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 // Right fill the mask of bits for this ADD to demand the most
1239 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001240 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001241 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1242 LHSKnownZero, LHSKnownOne, Depth+1) ||
1243 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 }
1247 }
1248 break;
1249 }
1250 case Instruction::Sub:
1251 // If the high-bits of this SUB are not demanded, then it does not demand
1252 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 // Right fill the mask of bits for this SUB to demand the most
1255 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001256 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001257 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1259 LHSKnownZero, LHSKnownOne, Depth+1) ||
1260 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001261 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001262 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001264 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1265 // the known zeros and ones.
1266 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 break;
1268 case Instruction::Shl:
1269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001270 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001271 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001274 return I;
1275 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 RHSKnownZero <<= ShiftAmt;
1277 RHSKnownOne <<= ShiftAmt;
1278 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001279 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001280 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 }
1282 break;
1283 case Instruction::LShr:
1284 // For a logical shift right
1285 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001286 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 return I;
1293 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1295 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001296 if (ShiftAmt) {
1297 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001298 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001299 RHSKnownZero |= HighBits; // high bits known zero.
1300 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 }
1302 break;
1303 case Instruction::AShr:
1304 // If this is an arithmetic shift right and only the low-bit is set, we can
1305 // always convert this into a logical shr, even if the shift amount is
1306 // variable. The low bit of the shift cannot be an input sign bit unless
1307 // the shift amount is >= the size of the datatype, which is undefined.
1308 if (DemandedMask == 1) {
1309 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001312 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001314
1315 // If the sign bit is the only bit demanded by this ashr, then there is no
1316 // need to do it, the shift doesn't change the high bit.
1317 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319
1320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001321 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001324 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001325 // If any of the "high bits" are demanded, we should set the sign bit as
1326 // demanded.
1327 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1328 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 return I;
1332 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001335 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1336 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1337
1338 // Handle the sign bits.
1339 APInt SignBit(APInt::getSignBit(BitWidth));
1340 // Adjust to where it is now in the mask.
1341 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1342
1343 // If the input sign bit is known to be zero, or if none of the top bits
1344 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001345 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001346 (HighBits & ~DemandedMask) == HighBits) {
1347 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1352 RHSKnownOne |= HighBits;
1353 }
1354 }
1355 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001356 case Instruction::SRem:
1357 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001358 APInt RA = Rem->getValue().abs();
1359 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001360 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001362
Nick Lewycky8e394322008-11-02 02:41:50 +00001363 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001364 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001366 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368
1369 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1370 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001371
1372 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001373
Chris Lattner886ab6c2009-01-31 08:15:18 +00001374 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001375 }
1376 }
1377 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001378 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001379 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1380 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001381 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1382 KnownZero2, KnownOne2, Depth+1) ||
1383 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001384 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001386
Chris Lattner455e9ab2009-01-21 18:09:24 +00001387 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001388 Leaders = std::max(Leaders,
1389 KnownZero2.countLeadingOnes());
1390 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001391 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001392 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001393 case Instruction::Call:
1394 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1395 switch (II->getIntrinsicID()) {
1396 default: break;
1397 case Intrinsic::bswap: {
1398 // If the only bits demanded come from one byte of the bswap result,
1399 // just shift the input byte into position to eliminate the bswap.
1400 unsigned NLZ = DemandedMask.countLeadingZeros();
1401 unsigned NTZ = DemandedMask.countTrailingZeros();
1402
1403 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1404 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1405 // have 14 leading zeros, round to 8.
1406 NLZ &= ~7;
1407 NTZ &= ~7;
1408 // If we need exactly one byte, we can do this transformation.
1409 if (BitWidth-NLZ-NTZ == 8) {
1410 unsigned ResultBit = NTZ;
1411 unsigned InputBit = BitWidth-NTZ-8;
1412
1413 // Replace this with either a left or right shift to get the byte into
1414 // the right place.
1415 Instruction *NewVal;
1416 if (InputBit > ResultBit)
1417 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001418 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001419 else
1420 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001421 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001422 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001423 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001424 }
1425
1426 // TODO: Could compute known zero/one bits based on the input.
1427 break;
1428 }
1429 }
1430 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001431 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001432 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001433 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001434
1435 // If the client is only demanding bits that we know, return the known
1436 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001437 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001438 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001439 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001440 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001441 return C;
1442 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001443 return false;
1444}
1445
Chris Lattner867b99f2006-10-05 06:55:50 +00001446
Mon P Wangaeb06d22008-11-10 04:46:22 +00001447/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001448/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001449/// actually used by the caller. This method analyzes which elements of the
1450/// operand are undef and returns that information in UndefElts.
1451///
1452/// If the information about demanded elements can be used to simplify the
1453/// operation, the operation is simplified, then the resultant value is
1454/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001455Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1456 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001458 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001459 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001460 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001461
1462 if (isa<UndefValue>(V)) {
1463 // If the entire vector is undefined, just return this info.
1464 UndefElts = EltMask;
1465 return 0;
1466 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1467 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001468 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001470
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001472 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1473 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001474 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001475
1476 std::vector<Constant*> Elts;
1477 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001478 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001480 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1482 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001483 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 } else { // Otherwise, defined.
1485 Elts.push_back(CP->getOperand(i));
1486 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001487
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001489 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 return NewCP != CP ? NewCP : 0;
1491 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001492 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001493 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001494
1495 // Check if this is identity. If so, return 0 since we are not simplifying
1496 // anything.
1497 if (DemandedElts == ((1ULL << VWidth) -1))
1498 return 0;
1499
Reid Spencer9d6565a2007-02-15 02:26:10 +00001500 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001501 Constant *Zero = Context->getNullValue(EltTy);
1502 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001504 for (unsigned i = 0; i != VWidth; ++i) {
1505 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1506 Elts.push_back(Elt);
1507 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001509 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 }
1511
Dan Gohman488fbfc2008-09-09 18:11:14 +00001512 // Limit search depth.
1513 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001514 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001515
1516 // If multiple users are using the root value, procede with
1517 // simplification conservatively assuming that all elements
1518 // are needed.
1519 if (!V->hasOneUse()) {
1520 // Quit if we find multiple users of a non-root value though.
1521 // They'll be handled when it's their turn to be visited by
1522 // the main instcombine process.
1523 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001525 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001526
1527 // Conservatively assume that all elements are needed.
1528 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001529 }
1530
1531 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001532 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001533
1534 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001535 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 Value *TmpV;
1537 switch (I->getOpcode()) {
1538 default: break;
1539
1540 case Instruction::InsertElement: {
1541 // If this is a variable index, we don't know which element it overwrites.
1542 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001543 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 if (Idx == 0) {
1545 // Note that we can't propagate undef elt info, because we don't know
1546 // which elt is getting updated.
1547 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1548 UndefElts2, Depth+1);
1549 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1550 break;
1551 }
1552
1553 // If this is inserting an element that isn't demanded, remove this
1554 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001555 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001556 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001557 return AddSoonDeadInstToWorklist(*I, 0);
1558
1559 // Otherwise, the element inserted overwrites whatever was there, so the
1560 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001561 APInt DemandedElts2 = DemandedElts;
1562 DemandedElts2.clear(IdxNo);
1563 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001564 UndefElts, Depth+1);
1565 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1566
1567 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001568 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 break;
1570 }
1571 case Instruction::ShuffleVector: {
1572 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001573 uint64_t LHSVWidth =
1574 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001575 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001577 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 unsigned MaskVal = Shuffle->getMaskValue(i);
1579 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001580 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001582 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001583 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001584 else
Evan Cheng388df622009-02-03 10:05:09 +00001585 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 }
1587 }
1588 }
1589
Nate Begeman7b254672009-02-11 22:36:25 +00001590 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001592 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594
Nate Begeman7b254672009-02-11 22:36:25 +00001595 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001596 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1597 UndefElts3, Depth+1);
1598 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1599
1600 bool NewUndefElts = false;
1601 for (unsigned i = 0; i < VWidth; i++) {
1602 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001603 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001604 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001605 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001606 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001607 NewUndefElts = true;
1608 UndefElts.set(i);
1609 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001611 if (UndefElts3[MaskVal - LHSVWidth]) {
1612 NewUndefElts = true;
1613 UndefElts.set(i);
1614 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001615 }
1616 }
1617
1618 if (NewUndefElts) {
1619 // Add additional discovered undefs.
1620 std::vector<Constant*> Elts;
1621 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001622 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001623 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001625 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001626 Shuffle->getMaskValue(i)));
1627 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001628 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001629 MadeChange = true;
1630 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001631 break;
1632 }
Chris Lattner69878332007-04-14 22:29:23 +00001633 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001634 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001635 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1636 if (!VTy) break;
1637 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001638 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001639 unsigned Ratio;
1640
1641 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001642 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001643 // elements as are demanded of us.
1644 Ratio = 1;
1645 InputDemandedElts = DemandedElts;
1646 } else if (VWidth > InVWidth) {
1647 // Untested so far.
1648 break;
1649
1650 // If there are more elements in the result than there are in the source,
1651 // then an input element is live if any of the corresponding output
1652 // elements are live.
1653 Ratio = VWidth/InVWidth;
1654 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001655 if (DemandedElts[OutIdx])
1656 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001657 }
1658 } else {
1659 // Untested so far.
1660 break;
1661
1662 // If there are more elements in the source than there are in the result,
1663 // then an input element is live if the corresponding output element is
1664 // live.
1665 Ratio = InVWidth/VWidth;
1666 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001667 if (DemandedElts[InIdx/Ratio])
1668 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001669 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001670
Chris Lattner69878332007-04-14 22:29:23 +00001671 // div/rem demand all inputs, because they don't want divide by zero.
1672 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1673 UndefElts2, Depth+1);
1674 if (TmpV) {
1675 I->setOperand(0, TmpV);
1676 MadeChange = true;
1677 }
1678
1679 UndefElts = UndefElts2;
1680 if (VWidth > InVWidth) {
1681 assert(0 && "Unimp");
1682 // If there are more elements in the result than there are in the source,
1683 // then an output element is undef if the corresponding input element is
1684 // undef.
1685 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001686 if (UndefElts2[OutIdx/Ratio])
1687 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001688 } else if (VWidth < InVWidth) {
1689 assert(0 && "Unimp");
1690 // If there are more elements in the source than there are in the result,
1691 // then a result element is undef if all of the corresponding input
1692 // elements are undef.
1693 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1694 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001695 if (!UndefElts2[InIdx]) // Not undef?
1696 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001697 }
1698 break;
1699 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001700 case Instruction::And:
1701 case Instruction::Or:
1702 case Instruction::Xor:
1703 case Instruction::Add:
1704 case Instruction::Sub:
1705 case Instruction::Mul:
1706 // div/rem demand all inputs, because they don't want divide by zero.
1707 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1708 UndefElts, Depth+1);
1709 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1710 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1711 UndefElts2, Depth+1);
1712 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1713
1714 // Output elements are undefined if both are undefined. Consider things
1715 // like undef&0. The result is known zero, not undef.
1716 UndefElts &= UndefElts2;
1717 break;
1718
1719 case Instruction::Call: {
1720 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1721 if (!II) break;
1722 switch (II->getIntrinsicID()) {
1723 default: break;
1724
1725 // Binary vector operations that work column-wise. A dest element is a
1726 // function of the corresponding input elements from the two inputs.
1727 case Intrinsic::x86_sse_sub_ss:
1728 case Intrinsic::x86_sse_mul_ss:
1729 case Intrinsic::x86_sse_min_ss:
1730 case Intrinsic::x86_sse_max_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
1732 case Intrinsic::x86_sse2_mul_sd:
1733 case Intrinsic::x86_sse2_min_sd:
1734 case Intrinsic::x86_sse2_max_sd:
1735 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1736 UndefElts, Depth+1);
1737 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1738 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1739 UndefElts2, Depth+1);
1740 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1741
1742 // If only the low elt is demanded and this is a scalarizable intrinsic,
1743 // scalarize it now.
1744 if (DemandedElts == 1) {
1745 switch (II->getIntrinsicID()) {
1746 default: break;
1747 case Intrinsic::x86_sse_sub_ss:
1748 case Intrinsic::x86_sse_mul_ss:
1749 case Intrinsic::x86_sse2_sub_sd:
1750 case Intrinsic::x86_sse2_mul_sd:
1751 // TODO: Lower MIN/MAX/ABS/etc
1752 Value *LHS = II->getOperand(1);
1753 Value *RHS = II->getOperand(2);
1754 // Extract the element as scalars.
1755 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1756 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1757
1758 switch (II->getIntrinsicID()) {
1759 default: assert(0 && "Case stmts out of sync!");
1760 case Intrinsic::x86_sse_sub_ss:
1761 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001762 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001763 II->getName()), *II);
1764 break;
1765 case Intrinsic::x86_sse_mul_ss:
1766 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001767 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001768 II->getName()), *II);
1769 break;
1770 }
1771
1772 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001773 InsertElementInst::Create(
1774 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001775 InsertNewInstBefore(New, *II);
1776 AddSoonDeadInstToWorklist(*II, 0);
1777 return New;
1778 }
1779 }
1780
1781 // Output elements are undefined if both are undefined. Consider things
1782 // like undef&0. The result is known zero, not undef.
1783 UndefElts &= UndefElts2;
1784 break;
1785 }
1786 break;
1787 }
1788 }
1789 return MadeChange ? I : 0;
1790}
1791
Dan Gohman45b4e482008-05-19 22:14:15 +00001792
Chris Lattner564a7272003-08-13 19:01:45 +00001793/// AssociativeOpt - Perform an optimization on an associative operator. This
1794/// function is designed to check a chain of associative operators for a
1795/// potential to apply a certain optimization. Since the optimization may be
1796/// applicable if the expression was reassociated, this checks the chain, then
1797/// reassociates the expression as necessary to expose the optimization
1798/// opportunity. This makes use of a special Functor, which must define
1799/// 'shouldApply' and 'apply' methods.
1800///
1801template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001802static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001803 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001804 unsigned Opcode = Root.getOpcode();
1805 Value *LHS = Root.getOperand(0);
1806
1807 // Quick check, see if the immediate LHS matches...
1808 if (F.shouldApply(LHS))
1809 return F.apply(Root);
1810
1811 // Otherwise, if the LHS is not of the same opcode as the root, return.
1812 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001813 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001814 // Should we apply this transform to the RHS?
1815 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1816
1817 // If not to the RHS, check to see if we should apply to the LHS...
1818 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1819 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1820 ShouldApply = true;
1821 }
1822
1823 // If the functor wants to apply the optimization to the RHS of LHSI,
1824 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1825 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001826 // Now all of the instructions are in the current basic block, go ahead
1827 // and perform the reassociation.
1828 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1829
1830 // First move the selected RHS to the LHS of the root...
1831 Root.setOperand(0, LHSI->getOperand(1));
1832
1833 // Make what used to be the LHS of the root be the user of the root...
1834 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001835 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001836 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001837 return 0;
1838 }
Chris Lattner65725312004-04-16 18:08:07 +00001839 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001840 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001841 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001842 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001843 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001844
1845 // Now propagate the ExtraOperand down the chain of instructions until we
1846 // get to LHSI.
1847 while (TmpLHSI != LHSI) {
1848 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001849 // Move the instruction to immediately before the chain we are
1850 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001851 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001852 ARI = NextLHSI;
1853
Chris Lattner564a7272003-08-13 19:01:45 +00001854 Value *NextOp = NextLHSI->getOperand(1);
1855 NextLHSI->setOperand(1, ExtraOperand);
1856 TmpLHSI = NextLHSI;
1857 ExtraOperand = NextOp;
1858 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001859
Chris Lattner564a7272003-08-13 19:01:45 +00001860 // Now that the instructions are reassociated, have the functor perform
1861 // the transformation...
1862 return F.apply(Root);
1863 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001864
Chris Lattner564a7272003-08-13 19:01:45 +00001865 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1866 }
1867 return 0;
1868}
1869
Dan Gohman844731a2008-05-13 00:00:25 +00001870namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001871
Nick Lewycky02d639f2008-05-23 04:34:58 +00001872// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001873struct AddRHS {
1874 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001875 LLVMContext *Context;
1876 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001877 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1878 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001879 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001880 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001881 }
1882};
1883
1884// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1885// iff C1&C2 == 0
1886struct AddMaskingAnd {
1887 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001888 LLVMContext *Context;
1889 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001890 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001891 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001892 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001893 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001894 }
1895 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001896 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001897 }
1898};
1899
Dan Gohman844731a2008-05-13 00:00:25 +00001900}
1901
Chris Lattner6e7ba452005-01-01 16:22:27 +00001902static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001903 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001904 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001905
Reid Spencer3da59db2006-11-27 01:05:10 +00001906 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001907 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 }
1909
Chris Lattner2eefe512004-04-09 19:05:30 +00001910 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001911 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1912 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001913
Chris Lattner2eefe512004-04-09 19:05:30 +00001914 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1915 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001916 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1917 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001918 }
1919
1920 Value *Op0 = SO, *Op1 = ConstOperand;
1921 if (!ConstIsRHS)
1922 std::swap(Op0, Op1);
1923 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001924 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001925 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001926 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001927 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1928 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001929 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001930 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001931 abort();
1932 }
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) &&
2117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
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
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
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;
2247 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2249 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;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002270 if (match(LHS, m_Not(m_Value(X)))) // ~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
2274 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002275 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 if (Anded == CRHS) {
2277 // See if all bits from the first bit set in the Add RHS up are included
2278 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002279 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280
2281 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002282 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002283
2284 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002285 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002286
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2288 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002289 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002290 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002292 }
2293 }
2294 }
2295
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002296 // Try to fold constant add into select arguments.
2297 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002298 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002299 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002300 }
2301
Reid Spencer1628cec2006-10-26 06:15:43 +00002302 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002303 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002304 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002305 CastInst *CI = dyn_cast<CastInst>(LHS);
2306 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002307 if (!CI) {
2308 CI = dyn_cast<CastInst>(RHS);
2309 Other = LHS;
2310 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002311 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002312 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002313 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002314 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002315 unsigned AS =
2316 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002317 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002318 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002319 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002320 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002321 }
2322 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002323
Chris Lattner42790482007-12-20 01:56:58 +00002324 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002325 {
2326 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002327 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002328 if (!SI) {
2329 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002330 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002331 }
Chris Lattner42790482007-12-20 01:56:58 +00002332 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002333 Value *TV = SI->getTrueValue();
2334 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002335 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002336
2337 // Can we fold the add into the argument of the select?
2338 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002339 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2340 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002341 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002342 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2343 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002344 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002345 }
2346 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002347
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002348 // Check for (add (sext x), y), see if we can merge this into an
2349 // integer add followed by a sext.
2350 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2351 // (add (sext x), cst) --> (sext (add x, cst'))
2352 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2353 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002354 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002355 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002356 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002357 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2358 // Insert the new, smaller add.
2359 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2360 CI, "addconv");
2361 InsertNewInstBefore(NewAdd, I);
2362 return new SExtInst(NewAdd, I.getType());
2363 }
2364 }
2365
2366 // (add (sext x), (sext y)) --> (sext (add int x, y))
2367 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2368 // Only do this if x/y have the same type, if at last one of them has a
2369 // single use (so we don't increase the number of sexts), and if the
2370 // integer add will not overflow.
2371 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2372 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2373 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2374 RHSConv->getOperand(0))) {
2375 // Insert the new integer add.
2376 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2377 RHSConv->getOperand(0),
2378 "addconv");
2379 InsertNewInstBefore(NewAdd, I);
2380 return new SExtInst(NewAdd, I.getType());
2381 }
2382 }
2383 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002384
2385 return Changed ? &I : 0;
2386}
2387
2388Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2389 bool Changed = SimplifyCommutative(I);
2390 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2391
2392 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2393 // X + 0 --> X
2394 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002395 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002396 (I.getType())->getValueAPF()))
2397 return ReplaceInstUsesWith(I, LHS);
2398 }
2399
2400 if (isa<PHINode>(LHS))
2401 if (Instruction *NV = FoldOpIntoPhi(I))
2402 return NV;
2403 }
2404
2405 // -A + B --> B - A
2406 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002407 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002408 return BinaryOperator::CreateFSub(RHS, LHSV);
2409
2410 // A + -B --> A - B
2411 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002412 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002413 return BinaryOperator::CreateFSub(LHS, V);
2414
2415 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2416 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2417 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2418 return ReplaceInstUsesWith(I, LHS);
2419
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002420 // Check for (add double (sitofp x), y), see if we can merge this into an
2421 // integer add followed by a promotion.
2422 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2423 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2424 // ... if the constant fits in the integer value. This is useful for things
2425 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2426 // requires a constant pool load, and generally allows the add to be better
2427 // instcombined.
2428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2429 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002430 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002431 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002432 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002433 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2434 // Insert the new integer add.
2435 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2436 CI, "addconv");
2437 InsertNewInstBefore(NewAdd, I);
2438 return new SIToFPInst(NewAdd, I.getType());
2439 }
2440 }
2441
2442 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2443 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2444 // Only do this if x/y have the same type, if at last one of them has a
2445 // single use (so we don't increase the number of int->fp conversions),
2446 // and if the integer add will not overflow.
2447 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2448 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2449 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2450 RHSConv->getOperand(0))) {
2451 // Insert the new integer add.
2452 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2453 RHSConv->getOperand(0),
2454 "addconv");
2455 InsertNewInstBefore(NewAdd, I);
2456 return new SIToFPInst(NewAdd, I.getType());
2457 }
2458 }
2459 }
2460
Chris Lattner7e708292002-06-25 16:13:24 +00002461 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002462}
2463
Chris Lattner7e708292002-06-25 16:13:24 +00002464Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002465 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002466
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002467 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002468 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002469
Chris Lattner233f7dc2002-08-12 21:17:25 +00002470 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002471 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002473
Chris Lattnere87597f2004-10-16 18:11:37 +00002474 if (isa<UndefValue>(Op0))
2475 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2476 if (isa<UndefValue>(Op1))
2477 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2478
Chris Lattnerd65460f2003-11-05 01:06:05 +00002479 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2480 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002481 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002482 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002483
Chris Lattnerd65460f2003-11-05 01:06:05 +00002484 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002485 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002486 if (match(Op1, m_Not(m_Value(X))))
Owen Andersond672ecb2009-07-03 00:17:18 +00002487 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002488
Chris Lattner76b7a062007-01-15 07:02:54 +00002489 // -(X >>u 31) -> (X >>s 31)
2490 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002491 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002492 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002493 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002494 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002495 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002496 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002497 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002498 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002499 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002500 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002501 }
2502 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002503 }
2504 else if (SI->getOpcode() == Instruction::AShr) {
2505 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2506 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002507 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002508 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002509 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002510 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002511 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002512 }
2513 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002514 }
2515 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002516 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002517
2518 // Try to fold constant sub into select arguments.
2519 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002520 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002521 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002522 }
2523
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002524 if (I.getType() == Type::Int1Ty)
2525 return BinaryOperator::CreateXor(Op0, Op1);
2526
Chris Lattner43d84d62005-04-07 16:15:25 +00002527 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002528 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002529 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002531 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002533 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2534 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2535 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002536 return BinaryOperator::CreateSub(
2537 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002538 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002539 }
2540
Chris Lattnerfd059242003-10-15 16:48:29 +00002541 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002542 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2543 // is not used by anyone else...
2544 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002545 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002546 // Swap the two operands of the subexpr...
2547 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2548 Op1I->setOperand(0, IIOp1);
2549 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002550
Chris Lattnera2881962003-02-18 19:28:33 +00002551 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002552 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002553 }
2554
2555 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2556 //
2557 if (Op1I->getOpcode() == Instruction::And &&
2558 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2559 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2560
Chris Lattnerf523d062004-06-09 05:08:07 +00002561 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002562 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2563 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002564 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002565
Reid Spencerac5209e2006-10-16 23:08:08 +00002566 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002567 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002568 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002569 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002570 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002571 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002572 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002573
Chris Lattnerad3448c2003-02-18 19:57:07 +00002574 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002575 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002576 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2577 Constant *CP1 =
2578 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002579 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002580 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002581 }
Chris Lattner40371712002-05-09 01:29:19 +00002582 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002583 }
Chris Lattnera2881962003-02-18 19:28:33 +00002584
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002585 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2586 if (Op0I->getOpcode() == Instruction::Add) {
2587 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2588 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2589 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2590 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2591 } else if (Op0I->getOpcode() == Instruction::Sub) {
2592 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2593 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002594 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002595 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002596
Chris Lattner50af16a2004-11-13 19:50:12 +00002597 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002598 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002599 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002600 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002601
Chris Lattner50af16a2004-11-13 19:50:12 +00002602 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002603 if (X == dyn_castFoldableMul(Op1, C2, Context))
2604 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002605 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002606 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002607}
2608
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002609Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2610 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2611
2612 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002613 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002614 return BinaryOperator::CreateFAdd(Op0, V);
2615
2616 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2617 if (Op1I->getOpcode() == Instruction::FAdd) {
2618 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2619 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2620 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2621 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2622 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002623 }
2624
2625 return 0;
2626}
2627
Chris Lattnera0141b92007-07-15 20:42:37 +00002628/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2629/// comparison only checks the sign bit. If it only checks the sign bit, set
2630/// TrueIfSigned if the result of the comparison is true when the input value is
2631/// signed.
2632static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2633 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002634 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002635 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2636 TrueIfSigned = true;
2637 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002638 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2639 TrueIfSigned = true;
2640 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002641 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2642 TrueIfSigned = false;
2643 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002644 case ICmpInst::ICMP_UGT:
2645 // True if LHS u> RHS and RHS == high-bit-mask - 1
2646 TrueIfSigned = true;
2647 return RHS->getValue() ==
2648 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2649 case ICmpInst::ICMP_UGE:
2650 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2651 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002652 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002653 default:
2654 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002655 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002656}
2657
Chris Lattner7e708292002-06-25 16:13:24 +00002658Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002659 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002660 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002661
Dan Gohman77b81fe2009-06-04 17:12:12 +00002662 // TODO: If Op1 is undef and Op0 is finite, return zero.
2663 if (!I.getType()->isFPOrFPVector() &&
2664 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002665 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002666
Chris Lattner233f7dc2002-08-12 21:17:25 +00002667 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002668 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2669 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002670
2671 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002672 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002673 if (SI->getOpcode() == Instruction::Shl)
2674 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002675 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002676 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002677
Zhou Sheng843f07672007-04-19 05:39:12 +00002678 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002679 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2680 if (CI->equalsInt(1)) // X * 1 == X
2681 return ReplaceInstUsesWith(I, Op0);
2682 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002683 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002684
Zhou Sheng97b52c22007-03-29 01:57:21 +00002685 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002686 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002688 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002689 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002690 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002691 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002692
2693 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2694 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2695 return BinaryOperator::CreateNeg(Op0, I.getName());
2696
2697 // As above, vector X*splat(1.0) -> X in all defined cases.
2698 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002699 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2700 if (CI->equalsInt(1))
2701 return ReplaceInstUsesWith(I, Op0);
2702 }
2703 }
Chris Lattnera2881962003-02-18 19:28:33 +00002704 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002705
2706 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2707 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002708 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002709 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002711 Op1, "tmp");
2712 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002713 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002714 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002715 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002716
2717 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002718
2719 // Try to fold constant mul into select arguments.
2720 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002721 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002722 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002723
2724 if (isa<PHINode>(Op0))
2725 if (Instruction *NV = FoldOpIntoPhi(I))
2726 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002727 }
2728
Owen Andersond672ecb2009-07-03 00:17:18 +00002729 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2730 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002732
Nick Lewycky0c730792008-11-21 07:33:58 +00002733 // (X / Y) * Y = X - (X % Y)
2734 // (X / Y) * -Y = (X % Y) - X
2735 {
2736 Value *Op1 = I.getOperand(1);
2737 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2738 if (!BO ||
2739 (BO->getOpcode() != Instruction::UDiv &&
2740 BO->getOpcode() != Instruction::SDiv)) {
2741 Op1 = Op0;
2742 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2743 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002744 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002745 if (BO && BO->hasOneUse() &&
2746 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2747 (BO->getOpcode() == Instruction::UDiv ||
2748 BO->getOpcode() == Instruction::SDiv)) {
2749 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2750
2751 Instruction *Rem;
2752 if (BO->getOpcode() == Instruction::UDiv)
2753 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2754 else
2755 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2756
2757 InsertNewInstBefore(Rem, I);
2758 Rem->takeName(BO);
2759
2760 if (Op1BO == Op1)
2761 return BinaryOperator::CreateSub(Op0BO, Rem);
2762 else
2763 return BinaryOperator::CreateSub(Rem, Op0BO);
2764 }
2765 }
2766
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002767 if (I.getType() == Type::Int1Ty)
2768 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2769
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002770 // If one of the operands of the multiply is a cast from a boolean value, then
2771 // we know the bool is either zero or one, so this is a 'masking' multiply.
2772 // See if we can simplify things based on how the boolean was originally
2773 // formed.
2774 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002775 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002776 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002777 BoolCast = CI;
2778 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002779 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002780 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 BoolCast = CI;
2782 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002783 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2785 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002786 bool TIS = false;
2787
Reid Spencere4d87aa2006-12-23 06:05:41 +00002788 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002789 // multiply into a shift/and combination.
2790 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002791 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2792 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002793 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002794 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002795 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002796 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002797 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002798 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002799 BoolCast->getOperand(0)->getName()+
2800 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002801
2802 // If the multiply type is not the same as the source type, sign extend
2803 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002804 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002805 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2806 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002807 Instruction::CastOps opcode =
2808 (SrcBits == DstBits ? Instruction::BitCast :
2809 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2810 V = InsertCastBefore(opcode, V, I.getType(), I);
2811 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002812
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002813 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002814 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002815 }
2816 }
2817 }
2818
Chris Lattner7e708292002-06-25 16:13:24 +00002819 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002820}
2821
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002822Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2823 bool Changed = SimplifyCommutative(I);
2824 Value *Op0 = I.getOperand(0);
2825
2826 // Simplify mul instructions with a constant RHS...
2827 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2828 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2829 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2830 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2831 if (Op1F->isExactlyValue(1.0))
2832 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2833 } else if (isa<VectorType>(Op1->getType())) {
2834 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2835 // As above, vector X*splat(1.0) -> X in all defined cases.
2836 if (Constant *Splat = Op1V->getSplatValue()) {
2837 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2838 if (F->isExactlyValue(1.0))
2839 return ReplaceInstUsesWith(I, Op0);
2840 }
2841 }
2842 }
2843
2844 // Try to fold constant mul into select arguments.
2845 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2846 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2847 return R;
2848
2849 if (isa<PHINode>(Op0))
2850 if (Instruction *NV = FoldOpIntoPhi(I))
2851 return NV;
2852 }
2853
Owen Andersond672ecb2009-07-03 00:17:18 +00002854 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2855 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002856 return BinaryOperator::CreateFMul(Op0v, Op1v);
2857
2858 return Changed ? &I : 0;
2859}
2860
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002861/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2862/// instruction.
2863bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2864 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2865
2866 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2867 int NonNullOperand = -1;
2868 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2869 if (ST->isNullValue())
2870 NonNullOperand = 2;
2871 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2872 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2873 if (ST->isNullValue())
2874 NonNullOperand = 1;
2875
2876 if (NonNullOperand == -1)
2877 return false;
2878
2879 Value *SelectCond = SI->getOperand(0);
2880
2881 // Change the div/rem to use 'Y' instead of the select.
2882 I.setOperand(1, SI->getOperand(NonNullOperand));
2883
2884 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2885 // problem. However, the select, or the condition of the select may have
2886 // multiple uses. Based on our knowledge that the operand must be non-zero,
2887 // propagate the known value for the select into other uses of it, and
2888 // propagate a known value of the condition into its other users.
2889
2890 // If the select and condition only have a single use, don't bother with this,
2891 // early exit.
2892 if (SI->use_empty() && SelectCond->hasOneUse())
2893 return true;
2894
2895 // Scan the current block backward, looking for other uses of SI.
2896 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2897
2898 while (BBI != BBFront) {
2899 --BBI;
2900 // If we found a call to a function, we can't assume it will return, so
2901 // information from below it cannot be propagated above it.
2902 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2903 break;
2904
2905 // Replace uses of the select or its condition with the known values.
2906 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2907 I != E; ++I) {
2908 if (*I == SI) {
2909 *I = SI->getOperand(NonNullOperand);
2910 AddToWorkList(BBI);
2911 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002912 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2913 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002914 AddToWorkList(BBI);
2915 }
2916 }
2917
2918 // If we past the instruction, quit looking for it.
2919 if (&*BBI == SI)
2920 SI = 0;
2921 if (&*BBI == SelectCond)
2922 SelectCond = 0;
2923
2924 // If we ran out of things to eliminate, break out of the loop.
2925 if (SelectCond == 0 && SI == 0)
2926 break;
2927
2928 }
2929 return true;
2930}
2931
2932
Reid Spencer1628cec2006-10-26 06:15:43 +00002933/// This function implements the transforms on div instructions that work
2934/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2935/// used by the visitors to those instructions.
2936/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002937Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002939
Chris Lattner50b2ca42008-02-19 06:12:18 +00002940 // undef / X -> 0 for integer.
2941 // undef / X -> undef for FP (the undef could be a snan).
2942 if (isa<UndefValue>(Op0)) {
2943 if (Op0->getType()->isFPOrFPVector())
2944 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002945 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002946 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002947
2948 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002949 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002950 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002951
Reid Spencer1628cec2006-10-26 06:15:43 +00002952 return 0;
2953}
Misha Brukmanfd939082005-04-21 23:48:37 +00002954
Reid Spencer1628cec2006-10-26 06:15:43 +00002955/// This function implements the transforms common to both integer division
2956/// instructions (udiv and sdiv). It is called by the visitors to those integer
2957/// division instructions.
2958/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002959Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2961
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002962 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002963 if (Op0 == Op1) {
2964 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002965 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002966 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002967 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002968 }
2969
Owen Andersond672ecb2009-07-03 00:17:18 +00002970 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002971 return ReplaceInstUsesWith(I, CI);
2972 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002973
Reid Spencer1628cec2006-10-26 06:15:43 +00002974 if (Instruction *Common = commonDivTransforms(I))
2975 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002976
2977 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2978 // This does not apply for fdiv.
2979 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2980 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002981
2982 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2983 // div X, 1 == X
2984 if (RHS->equalsInt(1))
2985 return ReplaceInstUsesWith(I, Op0);
2986
2987 // (X / C1) / C2 -> X / (C1*C2)
2988 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2989 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2990 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002991 if (MultiplyOverflows(RHS, LHSRHS,
2992 I.getOpcode()==Instruction::SDiv, Context))
2993 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002994 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002995 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002996 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002997 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002998
Reid Spencerbca0e382007-03-23 20:05:17 +00002999 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003000 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3001 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3002 return R;
3003 if (isa<PHINode>(Op0))
3004 if (Instruction *NV = FoldOpIntoPhi(I))
3005 return NV;
3006 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003007 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003008
Chris Lattnera2881962003-02-18 19:28:33 +00003009 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003010 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003011 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003012 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003013
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003014 // It can't be division by zero, hence it must be division by one.
3015 if (I.getType() == Type::Int1Ty)
3016 return ReplaceInstUsesWith(I, Op0);
3017
Nick Lewycky895f0852008-11-27 20:21:08 +00003018 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3019 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3020 // div X, 1 == X
3021 if (X->isOne())
3022 return ReplaceInstUsesWith(I, Op0);
3023 }
3024
Reid Spencer1628cec2006-10-26 06:15:43 +00003025 return 0;
3026}
3027
3028Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3030
3031 // Handle the integer div common cases
3032 if (Instruction *Common = commonIDivTransforms(I))
3033 return Common;
3034
Reid Spencer1628cec2006-10-26 06:15:43 +00003035 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003036 // X udiv C^2 -> X >> C
3037 // Check to see if this is an unsigned division with an exact power of 2,
3038 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003039 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003041 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003042
3043 // X udiv C, where C >= signbit
3044 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003045 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3046 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003047 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003048 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3049 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003050 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003051 }
3052
3053 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003054 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003055 if (RHSI->getOpcode() == Instruction::Shl &&
3056 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003057 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003058 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003059 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003060 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003061 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003062 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003063 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003064 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003065 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003066 }
3067 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003068 }
3069
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3071 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003072 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003074 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003075 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003076 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003078 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003079 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003080 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003081 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 Op0, TC, SI->getName()+".t");
3083 TSI = InsertNewInstBefore(TSI, I);
3084
3085 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003086 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003087 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003088 Op0, FC, SI->getName()+".f");
3089 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003090
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003091 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003092 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003093 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003095 return 0;
3096}
3097
Reid Spencer1628cec2006-10-26 06:15:43 +00003098Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3100
3101 // Handle the integer div common cases
3102 if (Instruction *Common = commonIDivTransforms(I))
3103 return Common;
3104
3105 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3106 // sdiv X, -1 == -X
3107 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003108 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003109 }
3110
3111 // If the sign bits of both operands are zero (i.e. we can prove they are
3112 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003113 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003114 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003115 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003116 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003117 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003118 }
3119 }
3120
3121 return 0;
3122}
3123
3124Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3125 return commonDivTransforms(I);
3126}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003127
Reid Spencer0a783f72006-11-02 01:53:59 +00003128/// This function implements the transforms on rem instructions that work
3129/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3130/// is used by the visitors to those instructions.
3131/// @brief Transforms common to all three rem instructions
3132Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003134
Chris Lattner50b2ca42008-02-19 06:12:18 +00003135 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3136 if (I.getType()->isFPOrFPVector())
3137 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003138 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003139 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003140 if (isa<UndefValue>(Op1))
3141 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003142
3143 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003144 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3145 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003146
Reid Spencer0a783f72006-11-02 01:53:59 +00003147 return 0;
3148}
3149
3150/// This function implements the transforms common to both integer remainder
3151/// instructions (urem and srem). It is called by the visitors to those integer
3152/// remainder instructions.
3153/// @brief Common integer remainder transforms
3154Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3156
3157 if (Instruction *common = commonRemTransforms(I))
3158 return common;
3159
Dale Johannesened6af242009-01-21 00:35:19 +00003160 // 0 % X == 0 for integer, we don't need to preserve faults!
3161 if (Constant *LHS = dyn_cast<Constant>(Op0))
3162 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003163 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003164
Chris Lattner857e8cd2004-12-12 21:48:58 +00003165 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003166 // X % 0 == undef, we don't need to preserve faults!
3167 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003168 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003169
Chris Lattnera2881962003-02-18 19:28:33 +00003170 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003171 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003172
Chris Lattner97943922006-02-28 05:49:21 +00003173 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3174 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3175 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3176 return R;
3177 } else if (isa<PHINode>(Op0I)) {
3178 if (Instruction *NV = FoldOpIntoPhi(I))
3179 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003180 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003181
3182 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003183 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003184 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003185 }
Chris Lattnera2881962003-02-18 19:28:33 +00003186 }
3187
Reid Spencer0a783f72006-11-02 01:53:59 +00003188 return 0;
3189}
3190
3191Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3192 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3193
3194 if (Instruction *common = commonIRemTransforms(I))
3195 return common;
3196
3197 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3198 // X urem C^2 -> X and C
3199 // Check to see if this is an unsigned remainder with an exact power of 2,
3200 // if so, convert to a bitwise and.
3201 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003202 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003203 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 }
3205
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003206 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3208 if (RHSI->getOpcode() == Instruction::Shl &&
3209 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003210 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003211 Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003212 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003213 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003214 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003215 }
3216 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003218
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3220 // where C1&C2 are powers of two.
3221 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3222 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3223 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3224 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003225 if ((STO->getValue().isPowerOf2()) &&
3226 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003227 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003228 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3229 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003231 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3232 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003233 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003234 }
3235 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003236 }
3237
Chris Lattner3f5b8772002-05-06 16:14:14 +00003238 return 0;
3239}
3240
Reid Spencer0a783f72006-11-02 01:53:59 +00003241Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3243
Dan Gohmancff55092007-11-05 23:16:33 +00003244 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 if (Instruction *common = commonIRemTransforms(I))
3246 return common;
3247
Owen Andersond672ecb2009-07-03 00:17:18 +00003248 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003249 if (!isa<Constant>(RHSNeg) ||
3250 (isa<ConstantInt>(RHSNeg) &&
3251 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003252 // X % -Y -> X % Y
3253 AddUsesToWorkList(I);
3254 I.setOperand(1, RHSNeg);
3255 return &I;
3256 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003257
Dan Gohmancff55092007-11-05 23:16:33 +00003258 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003259 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003260 if (I.getType()->isInteger()) {
3261 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3262 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3263 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003264 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003265 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003266 }
3267
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003269 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3270 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003271
Nick Lewycky9dce8732008-12-20 16:48:00 +00003272 bool hasNegative = false;
3273 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3274 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3275 if (RHS->getValue().isNegative())
3276 hasNegative = true;
3277
3278 if (hasNegative) {
3279 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003280 for (unsigned i = 0; i != VWidth; ++i) {
3281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3282 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003283 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003284 else
3285 Elts[i] = RHS;
3286 }
3287 }
3288
Owen Andersond672ecb2009-07-03 00:17:18 +00003289 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003290 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003291 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003292 I.setOperand(1, NewRHSV);
3293 return &I;
3294 }
3295 }
3296 }
3297
Reid Spencer0a783f72006-11-02 01:53:59 +00003298 return 0;
3299}
3300
3301Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003302 return commonRemTransforms(I);
3303}
3304
Chris Lattner457dd822004-06-09 07:59:58 +00003305// isOneBitSet - Return true if there is exactly one bit set in the specified
3306// constant.
3307static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003308 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003309}
3310
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003311// isHighOnes - Return true if the constant is of the form 1+0+.
3312// This is the same as lowones(~X).
3313static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003314 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003315}
3316
Reid Spencere4d87aa2006-12-23 06:05:41 +00003317/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003318/// are carefully arranged to allow folding of expressions such as:
3319///
3320/// (A < B) | (A > B) --> (A != B)
3321///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003322/// Note that this is only valid if the first and second predicates have the
3323/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003324///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325/// Three bits are used to represent the condition, as follows:
3326/// 0 A > B
3327/// 1 A == B
3328/// 2 A < B
3329///
3330/// <=> Value Definition
3331/// 000 0 Always false
3332/// 001 1 A > B
3333/// 010 2 A == B
3334/// 011 3 A >= B
3335/// 100 4 A < B
3336/// 101 5 A != B
3337/// 110 6 A <= B
3338/// 111 7 Always true
3339///
3340static unsigned getICmpCode(const ICmpInst *ICI) {
3341 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003342 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003343 case ICmpInst::ICMP_UGT: return 1; // 001
3344 case ICmpInst::ICMP_SGT: return 1; // 001
3345 case ICmpInst::ICMP_EQ: return 2; // 010
3346 case ICmpInst::ICMP_UGE: return 3; // 011
3347 case ICmpInst::ICMP_SGE: return 3; // 011
3348 case ICmpInst::ICMP_ULT: return 4; // 100
3349 case ICmpInst::ICMP_SLT: return 4; // 100
3350 case ICmpInst::ICMP_NE: return 5; // 101
3351 case ICmpInst::ICMP_ULE: return 6; // 110
3352 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003353 // True -> 7
3354 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003356 return 0;
3357 }
3358}
3359
Evan Cheng8db90722008-10-14 17:15:11 +00003360/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3361/// predicate into a three bit mask. It also returns whether it is an ordered
3362/// predicate by reference.
3363static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3364 isOrdered = false;
3365 switch (CC) {
3366 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3367 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003368 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3369 case FCmpInst::FCMP_UGT: return 1; // 001
3370 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3371 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003372 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3373 case FCmpInst::FCMP_UGE: return 3; // 011
3374 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3375 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003376 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3377 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003378 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3379 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003380 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003381 default:
3382 // Not expecting FCMP_FALSE and FCMP_TRUE;
3383 assert(0 && "Unexpected FCmp predicate!");
3384 return 0;
3385 }
3386}
3387
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388/// getICmpValue - This is the complement of getICmpCode, which turns an
3389/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003390/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003391/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003392static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003393 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 switch (code) {
3395 default: assert(0 && "Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003396 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 case 1:
3398 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003399 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 else
Owen Anderson333c4002009-07-09 23:48:35 +00003401 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3402 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 case 3:
3404 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003405 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 else
Owen Anderson333c4002009-07-09 23:48:35 +00003407 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 case 4:
3409 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3413 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 case 6:
3415 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003416 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 else
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003419 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003420 }
3421}
3422
Evan Cheng8db90722008-10-14 17:15:11 +00003423/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3424/// opcode and two operands into either a FCmp instruction. isordered is passed
3425/// in to determine which kind of predicate to use in the new fcmp instruction.
3426static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003427 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003428 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003429 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003430 case 0:
3431 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 else
Owen Anderson333c4002009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 case 1:
3436 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003438 else
Owen Anderson333c4002009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003440 case 2:
3441 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003443 else
Owen Anderson333c4002009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 case 3:
3446 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003448 else
Owen Anderson333c4002009-07-09 23:48:35 +00003449 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 case 4:
3451 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003452 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 else
Owen Anderson333c4002009-07-09 23:48:35 +00003454 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003455 case 5:
3456 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003457 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003458 else
Owen Anderson333c4002009-07-09 23:48:35 +00003459 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003460 case 6:
3461 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003462 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 else
Owen Anderson333c4002009-07-09 23:48:35 +00003464 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003465 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003466 }
3467}
3468
Chris Lattnerb9553d62008-11-16 04:55:20 +00003469/// PredicatesFoldable - Return true if both predicates match sign or if at
3470/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003471static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3472 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003473 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3474 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475}
3476
3477namespace {
3478// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3479struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003480 InstCombiner &IC;
3481 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003482 ICmpInst::Predicate pred;
3483 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3484 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3485 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003486 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003487 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3488 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003489 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3490 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003491 return false;
3492 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 Instruction *apply(Instruction &Log) const {
3494 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3495 if (ICI->getOperand(0) != LHS) {
3496 assert(ICI->getOperand(1) == LHS);
3497 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003498 }
3499
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003500 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003502 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003503 unsigned Code;
3504 switch (Log.getOpcode()) {
3505 case Instruction::And: Code = LHSCode & RHSCode; break;
3506 case Instruction::Or: Code = LHSCode | RHSCode; break;
3507 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003508 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003509 }
3510
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003511 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3512 ICmpInst::isSignedPredicate(ICI->getPredicate());
3513
Owen Andersond672ecb2009-07-03 00:17:18 +00003514 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003515 if (Instruction *I = dyn_cast<Instruction>(RV))
3516 return I;
3517 // Otherwise, it's a constant boolean value...
3518 return IC.ReplaceInstUsesWith(Log, RV);
3519 }
3520};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003521} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003522
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3524// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003525// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003526Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003527 ConstantInt *OpRHS,
3528 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003529 BinaryOperator &TheAnd) {
3530 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003531 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003532 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003533 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003534
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 switch (Op->getOpcode()) {
3536 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003537 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003539 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003540 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003541 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003542 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 }
3544 break;
3545 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003546 if (Together == AndRHS) // (X | C) & C --> C
3547 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003548
Chris Lattner6e7ba452005-01-01 16:22:27 +00003549 if (Op->hasOneUse() && Together != OpRHS) {
3550 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003552 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003553 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 }
3556 break;
3557 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003558 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Adding a one to a single bit bit-field should be turned into an XOR
3560 // of the bit. First thing to check is to see if this AND is with a
3561 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003562 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563
3564 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003565 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 // Ok, at this point, we know that we are masking the result of the
3567 // ADD down to exactly one bit. If the constant we are adding has
3568 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003569 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003570
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003571 // Check to see if any bits below the one bit set in AndRHSV are set.
3572 if ((AddRHS & (AndRHSV-1)) == 0) {
3573 // If not, the only thing that can effect the output of the AND is
3574 // the bit specified by AndRHSV. If that bit is set, the effect of
3575 // the XOR is to toggle the bit. If it is clear, then the ADD has
3576 // no effect.
3577 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3578 TheAnd.setOperand(0, X);
3579 return &TheAnd;
3580 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003581 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003583 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003584 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003585 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003586 }
3587 }
3588 }
3589 }
3590 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003591
3592 case Instruction::Shl: {
3593 // We know that the AND will not produce any of the bits shifted in, so if
3594 // the anded constant includes them, clear them now!
3595 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003599 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003600
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 if (CI->getValue() == ShlMask) {
3602 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003603 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3604 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003605 TheAnd.setOperand(1, CI);
3606 return &TheAnd;
3607 }
3608 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003609 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003610 case Instruction::LShr:
3611 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003612 // We know that the AND will not produce any of the bits shifted in, so if
3613 // the anded constant includes them, clear them now! This only applies to
3614 // unsigned shifts, because a signed shr may bring in set bits!
3615 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003616 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003617 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003618 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003619 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003620
Zhou Sheng290bec52007-03-29 08:15:12 +00003621 if (CI->getValue() == ShrMask) {
3622 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003623 return ReplaceInstUsesWith(TheAnd, Op);
3624 } else if (CI != AndRHS) {
3625 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3626 return &TheAnd;
3627 }
3628 break;
3629 }
3630 case Instruction::AShr:
3631 // Signed shr.
3632 // See if this is shifting in some sign extension, then masking it out
3633 // with an and.
3634 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003635 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003636 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003637 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003638 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003639 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003640 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003641 // Make the argument unsigned.
3642 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003643 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003644 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003645 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003646 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003647 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003648 }
3649 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003650 }
3651 return 0;
3652}
3653
Chris Lattner8b170942002-08-09 23:47:40 +00003654
Chris Lattnera96879a2004-09-29 17:40:11 +00003655/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3656/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3658/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003659/// insert new instructions.
3660Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 bool isSigned, bool Inside,
3662 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003663 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003664 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003665 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666
Chris Lattnera96879a2004-09-29 17:40:11 +00003667 if (Inside) {
3668 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003669 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003670
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003672 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003673 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003675 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 }
3677
3678 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003679 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003681 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003682 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003683 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003684 }
3685
3686 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003687 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003688
Reid Spencere4e40032007-03-21 23:19:50 +00003689 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003690 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003691 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 ICmpInst::Predicate pred = (isSigned ?
3693 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003694 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003696
Reid Spencere4e40032007-03-21 23:19:50 +00003697 // Emit V-Lo >u Hi-1-Lo
3698 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003699 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003700 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003701 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003702 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003703 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003704}
3705
Chris Lattner7203e152005-09-18 07:22:02 +00003706// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3707// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3708// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3709// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003710static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003711 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003712 uint32_t BitWidth = Val->getType()->getBitWidth();
3713 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003714
3715 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003716 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003717 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003718 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003719 return true;
3720}
3721
Chris Lattner7203e152005-09-18 07:22:02 +00003722/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3723/// where isSub determines whether the operator is a sub. If we can fold one of
3724/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003725///
3726/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3727/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3729///
3730/// return (A +/- B).
3731///
3732Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003733 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003734 Instruction &I) {
3735 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3736 if (!LHSI || LHSI->getNumOperands() != 2 ||
3737 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3738
3739 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3740
3741 switch (LHSI->getOpcode()) {
3742 default: return 0;
3743 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003744 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003745 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) ==
3748 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003749 break;
3750
3751 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3752 // part, we don't need any explicit masks to take them out of A. If that
3753 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003754 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003755 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003756 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003757 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003758 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003759 break;
3760 }
3761 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003762 return 0;
3763 case Instruction::Or:
3764 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003765 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003766 if ((Mask->getValue().countLeadingZeros() +
3767 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003768 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003769 break;
3770 return 0;
3771 }
3772
3773 Instruction *New;
3774 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003775 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003776 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003777 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003778 return InsertNewInstBefore(New, I);
3779}
3780
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003781/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3782Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3783 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003784 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003785 ConstantInt *LHSCst, *RHSCst;
3786 ICmpInst::Predicate LHSCC, RHSCC;
3787
Chris Lattnerea065fb2008-11-16 05:10:52 +00003788 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003790 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003791 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003792
3793 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3794 // where C is a power of 2
3795 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3796 LHSCst->getValue().isPowerOf2()) {
3797 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3798 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003799 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003800 }
3801
3802 // From here on, we only handle:
3803 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3804 if (Val != Val2) return 0;
3805
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003806 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3807 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3808 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3809 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3810 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3811 return 0;
3812
3813 // We can't fold (ugt x, C) & (sgt x, C2).
3814 if (!PredicatesFoldable(LHSCC, RHSCC))
3815 return 0;
3816
3817 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003818 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003819 if (ICmpInst::isSignedPredicate(LHSCC) ||
3820 (ICmpInst::isEquality(LHSCC) &&
3821 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003822 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003824 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3825
3826 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003827 std::swap(LHS, RHS);
3828 std::swap(LHSCst, RHSCst);
3829 std::swap(LHSCC, RHSCC);
3830 }
3831
3832 // At this point, we know we have have two icmp instructions
3833 // comparing a value against two constants and and'ing the result
3834 // together. Because of the above check, we know that we only have
3835 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3836 // (from the FoldICmpLogical check above), that the two constants
3837 // are not equal and that the larger constant is on the RHS
3838 assert(LHSCst != RHSCst && "Compares not folded above?");
3839
3840 switch (LHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
3842 case ICmpInst::ICMP_EQ:
3843 switch (RHSCC) {
3844 default: assert(0 && "Unknown integer condition code!");
3845 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3846 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3847 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003848 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003849 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3850 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3851 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3852 return ReplaceInstUsesWith(I, LHS);
3853 }
3854 case ICmpInst::ICMP_NE:
3855 switch (RHSCC) {
3856 default: assert(0 && "Unknown integer condition code!");
3857 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003858 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003859 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003860 break; // (X != 13 & X u< 15) -> no change
3861 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003862 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003863 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003864 break; // (X != 13 & X s< 15) -> no change
3865 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3866 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3867 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3868 return ReplaceInstUsesWith(I, RHS);
3869 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003870 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3871 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003872 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3873 Val->getName()+".off");
3874 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003875 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003876 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 }
3878 break; // (X != 13 & X != 15) -> no change
3879 }
3880 break;
3881 case ICmpInst::ICMP_ULT:
3882 switch (RHSCC) {
3883 default: assert(0 && "Unknown integer condition code!");
3884 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3885 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003886 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003887 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3888 break;
3889 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3890 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3891 return ReplaceInstUsesWith(I, LHS);
3892 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3893 break;
3894 }
3895 break;
3896 case ICmpInst::ICMP_SLT:
3897 switch (RHSCC) {
3898 default: assert(0 && "Unknown integer condition code!");
3899 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3900 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003901 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3903 break;
3904 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3905 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3906 return ReplaceInstUsesWith(I, LHS);
3907 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3908 break;
3909 }
3910 break;
3911 case ICmpInst::ICMP_UGT:
3912 switch (RHSCC) {
3913 default: assert(0 && "Unknown integer condition code!");
3914 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3915 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3916 return ReplaceInstUsesWith(I, RHS);
3917 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003920 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003921 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003923 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003924 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3925 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3927 break;
3928 }
3929 break;
3930 case ICmpInst::ICMP_SGT:
3931 switch (RHSCC) {
3932 default: assert(0 && "Unknown integer condition code!");
3933 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3934 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3935 return ReplaceInstUsesWith(I, RHS);
3936 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3937 break;
3938 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003939 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003940 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003941 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003942 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003943 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3944 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003945 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3946 break;
3947 }
3948 break;
3949 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003950
3951 return 0;
3952}
3953
3954
Chris Lattner7e708292002-06-25 16:13:24 +00003955Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003956 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003958
Chris Lattnere87597f2004-10-16 18:11:37 +00003959 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003960 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003961
Chris Lattner6e7ba452005-01-01 16:22:27 +00003962 // and X, X = X
3963 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003964 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003965
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003966 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003967 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003968 if (SimplifyDemandedInstructionBits(I))
3969 return &I;
3970 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003971 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003972 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003973 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003974 } else if (isa<ConstantAggregateZero>(Op1)) {
3975 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003976 }
3977 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003978
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003979 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003980 const APInt& AndRHSMask = AndRHS->getValue();
3981 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003982
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003983 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003984 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003985 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003986 Value *Op0LHS = Op0I->getOperand(0);
3987 Value *Op0RHS = Op0I->getOperand(1);
3988 switch (Op0I->getOpcode()) {
3989 case Instruction::Xor:
3990 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003991 // If the mask is only needed on one incoming arm, push it up.
3992 if (Op0I->hasOneUse()) {
3993 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3994 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003995 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003996 Op0RHS->getName()+".masked");
3997 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003999 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004000 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004001 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004002 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4003 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004004 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004005 Op0LHS->getName()+".masked");
4006 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004007 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004008 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4009 }
4010 }
4011
Chris Lattner6e7ba452005-01-01 16:22:27 +00004012 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004013 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004014 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4015 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4016 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4017 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004018 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004019 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004021 break;
4022
4023 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004024 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4025 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4026 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4027 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004028 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004029
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004030 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4031 // has 1's for all bits that the subtraction with A might affect.
4032 if (Op0I->hasOneUse()) {
4033 uint32_t BitWidth = AndRHSMask.getBitWidth();
4034 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4035 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4036
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004037 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004038 if (!(A && A->isZero()) && // avoid infinite recursion.
4039 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004040 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4041 InsertNewInstBefore(NewNeg, I);
4042 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4043 }
4044 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004045 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004046
4047 case Instruction::Shl:
4048 case Instruction::LShr:
4049 // (1 << x) & 1 --> zext(x == 0)
4050 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004051 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004052 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4053 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004054 InsertNewInstBefore(NewICmp, I);
4055 return new ZExtInst(NewICmp, I.getType());
4056 }
4057 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004058 }
4059
Chris Lattner58403262003-07-23 19:25:52 +00004060 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004061 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004062 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004063 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004064 // If this is an integer truncation or change from signed-to-unsigned, and
4065 // if the source is an and/or with immediate, transform it. This
4066 // frequently occurs for bitfield accesses.
4067 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004068 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004069 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004070 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004071 if (CastOp->getOpcode() == Instruction::And) {
4072 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004073 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4074 // This will fold the two constants together, which may allow
4075 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004077 CastOp->getOperand(0), I.getType(),
4078 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004079 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004080 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004081 Constant *C3 =
4082 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4083 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004084 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004085 } else if (CastOp->getOpcode() == Instruction::Or) {
4086 // Change: and (cast (or X, C1) to T), C2
4087 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004088 Constant *C3 =
4089 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4090 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4091 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004092 return ReplaceInstUsesWith(I, AndRHS);
4093 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004094 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004095 }
Chris Lattner06782f82003-07-23 19:36:21 +00004096 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004097
4098 // Try to fold constant and into select arguments.
4099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004101 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004102 if (isa<PHINode>(Op0))
4103 if (Instruction *NV = FoldOpIntoPhi(I))
4104 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004105 }
4106
Owen Andersond672ecb2009-07-03 00:17:18 +00004107 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4108 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004109
Chris Lattner5b62aa72004-06-18 06:07:51 +00004110 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004111 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004112
Misha Brukmancb6267b2004-07-30 12:50:08 +00004113 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004114 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004115 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004116 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004117 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004118 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004119 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004120
4121 {
Chris Lattner003b6202007-06-15 05:58:24 +00004122 Value *A = 0, *B = 0, *C = 0, *D = 0;
4123 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004124 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4125 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004126
4127 // (A|B) & ~(A&B) -> A^B
4128 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4129 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004130 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004131 }
4132 }
4133
4134 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004135 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4136 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004137
4138 // ~(A&B) & (A|B) -> A^B
4139 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4140 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004141 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004142 }
4143 }
Chris Lattner64daab52006-04-01 08:03:55 +00004144
4145 if (Op0->hasOneUse() &&
4146 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4147 if (A == Op1) { // (A^B)&A -> A&(A^B)
4148 I.swapOperands(); // Simplify below
4149 std::swap(Op0, Op1);
4150 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4151 cast<BinaryOperator>(Op0)->swapOperands();
4152 I.swapOperands(); // Simplify below
4153 std::swap(Op0, Op1);
4154 }
4155 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004156
Chris Lattner64daab52006-04-01 08:03:55 +00004157 if (Op1->hasOneUse() &&
4158 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4159 if (B == Op0) { // B&(A^B) -> B&(B^A)
4160 cast<BinaryOperator>(Op1)->swapOperands();
4161 std::swap(A, B);
4162 }
4163 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004164 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004165 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004166 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004167 }
4168 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004169
4170 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004171 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4172 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4173 return BinaryOperator::CreateAnd(A, Op1);
4174 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4175 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4176 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004177 }
4178
Reid Spencere4d87aa2006-12-23 06:05:41 +00004179 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4180 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004181 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004182 return R;
4183
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004184 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4185 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4186 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004187 }
4188
Chris Lattner6fc205f2006-05-05 06:39:07 +00004189 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004190 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4191 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4192 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4193 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004194 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004195 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004196 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4197 I.getType(), TD) &&
4198 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4199 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004200 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004201 Op1C->getOperand(0),
4202 I.getName());
4203 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004204 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004205 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004206 }
Chris Lattnere511b742006-11-14 07:46:50 +00004207
4208 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004209 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4210 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4211 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004212 SI0->getOperand(1) == SI1->getOperand(1) &&
4213 (SI0->hasOneUse() || SI1->hasOneUse())) {
4214 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004215 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004216 SI1->getOperand(0),
4217 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004218 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004219 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004220 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004221 }
4222
Evan Cheng8db90722008-10-14 17:15:11 +00004223 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004224 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4225 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4226 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004227 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4228 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004229 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4230 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4231 // If either of the constants are nans, then the whole thing returns
4232 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004233 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004234 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004235 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4236 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004237 }
Evan Cheng8db90722008-10-14 17:15:11 +00004238 } else {
4239 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4240 FCmpInst::Predicate Op0CC, Op1CC;
4241 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4242 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004243 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4244 // Swap RHS operands to match LHS.
4245 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4246 std::swap(Op1LHS, Op1RHS);
4247 }
Evan Cheng8db90722008-10-14 17:15:11 +00004248 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4249 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4250 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004251 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4252 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004253 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4254 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004255 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004256 else if (Op0CC == FCmpInst::FCMP_TRUE)
4257 return ReplaceInstUsesWith(I, Op1);
4258 else if (Op1CC == FCmpInst::FCMP_TRUE)
4259 return ReplaceInstUsesWith(I, Op0);
4260 bool Op0Ordered;
4261 bool Op1Ordered;
4262 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4263 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4264 if (Op1Pred == 0) {
4265 std::swap(Op0, Op1);
4266 std::swap(Op0Pred, Op1Pred);
4267 std::swap(Op0Ordered, Op1Ordered);
4268 }
4269 if (Op0Pred == 0) {
4270 // uno && ueq -> uno && (uno || eq) -> ueq
4271 // ord && olt -> ord && (ord && lt) -> olt
4272 if (Op0Ordered == Op1Ordered)
4273 return ReplaceInstUsesWith(I, Op1);
4274 // uno && oeq -> uno && (ord && eq) -> false
4275 // uno && ord -> false
4276 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004277 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004278 // ord && ueq -> ord && (uno || eq) -> oeq
4279 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004280 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004281 }
4282 }
4283 }
4284 }
Chris Lattner99c65742007-10-24 05:38:08 +00004285 }
4286 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004287
Chris Lattner7e708292002-06-25 16:13:24 +00004288 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004289}
4290
Chris Lattner8c34cd22008-10-05 02:13:19 +00004291/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4292/// capable of providing pieces of a bswap. The subexpression provides pieces
4293/// of a bswap if it is proven that each of the non-zero bytes in the output of
4294/// the expression came from the corresponding "byte swapped" byte in some other
4295/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4296/// we know that the expression deposits the low byte of %X into the high byte
4297/// of the bswap result and that all other bytes are zero. This expression is
4298/// accepted, the high byte of ByteValues is set to X to indicate a correct
4299/// match.
4300///
4301/// This function returns true if the match was unsuccessful and false if so.
4302/// On entry to the function the "OverallLeftShift" is a signed integer value
4303/// indicating the number of bytes that the subexpression is later shifted. For
4304/// example, if the expression is later right shifted by 16 bits, the
4305/// OverallLeftShift value would be -2 on entry. This is used to specify which
4306/// byte of ByteValues is actually being set.
4307///
4308/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4309/// byte is masked to zero by a user. For example, in (X & 255), X will be
4310/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4311/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4312/// always in the local (OverallLeftShift) coordinate space.
4313///
4314static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4315 SmallVector<Value*, 8> &ByteValues) {
4316 if (Instruction *I = dyn_cast<Instruction>(V)) {
4317 // If this is an or instruction, it may be an inner node of the bswap.
4318 if (I->getOpcode() == Instruction::Or) {
4319 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4320 ByteValues) ||
4321 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4322 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004323 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004324
4325 // If this is a logical shift by a constant multiple of 8, recurse with
4326 // OverallLeftShift and ByteMask adjusted.
4327 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4328 unsigned ShAmt =
4329 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4330 // Ensure the shift amount is defined and of a byte value.
4331 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4332 return true;
4333
4334 unsigned ByteShift = ShAmt >> 3;
4335 if (I->getOpcode() == Instruction::Shl) {
4336 // X << 2 -> collect(X, +2)
4337 OverallLeftShift += ByteShift;
4338 ByteMask >>= ByteShift;
4339 } else {
4340 // X >>u 2 -> collect(X, -2)
4341 OverallLeftShift -= ByteShift;
4342 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004343 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004344 }
4345
4346 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4347 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4348
4349 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4350 ByteValues);
4351 }
4352
4353 // If this is a logical 'and' with a mask that clears bytes, clear the
4354 // corresponding bytes in ByteMask.
4355 if (I->getOpcode() == Instruction::And &&
4356 isa<ConstantInt>(I->getOperand(1))) {
4357 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4358 unsigned NumBytes = ByteValues.size();
4359 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4360 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4361
4362 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4363 // If this byte is masked out by a later operation, we don't care what
4364 // the and mask is.
4365 if ((ByteMask & (1 << i)) == 0)
4366 continue;
4367
4368 // If the AndMask is all zeros for this byte, clear the bit.
4369 APInt MaskB = AndMask & Byte;
4370 if (MaskB == 0) {
4371 ByteMask &= ~(1U << i);
4372 continue;
4373 }
4374
4375 // If the AndMask is not all ones for this byte, it's not a bytezap.
4376 if (MaskB != Byte)
4377 return true;
4378
4379 // Otherwise, this byte is kept.
4380 }
4381
4382 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4383 ByteValues);
4384 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004385 }
4386
Chris Lattner8c34cd22008-10-05 02:13:19 +00004387 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4388 // the input value to the bswap. Some observations: 1) if more than one byte
4389 // is demanded from this input, then it could not be successfully assembled
4390 // into a byteswap. At least one of the two bytes would not be aligned with
4391 // their ultimate destination.
4392 if (!isPowerOf2_32(ByteMask)) return true;
4393 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004394
Chris Lattner8c34cd22008-10-05 02:13:19 +00004395 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4396 // is demanded, it needs to go into byte 0 of the result. This means that the
4397 // byte needs to be shifted until it lands in the right byte bucket. The
4398 // shift amount depends on the position: if the byte is coming from the high
4399 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4400 // low part, it must be shifted left.
4401 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4402 if (InputByteNo < ByteValues.size()/2) {
4403 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4404 return true;
4405 } else {
4406 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4407 return true;
4408 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409
4410 // If the destination byte value is already defined, the values are or'd
4411 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004412 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004413 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004414 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004415 return false;
4416}
4417
4418/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4419/// If so, insert the new bswap intrinsic and return it.
4420Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004421 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004422 if (!ITy || ITy->getBitWidth() % 16 ||
4423 // ByteMask only allows up to 32-byte values.
4424 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004425 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004426
4427 /// ByteValues - For each byte of the result, we keep track of which value
4428 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004429 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004430 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431
4432 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004433 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4434 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004435 return 0;
4436
4437 // Check to see if all of the bytes come from the same value.
4438 Value *V = ByteValues[0];
4439 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4440
4441 // Check to make sure that all of the bytes come from the same value.
4442 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4443 if (ByteValues[i] != V)
4444 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004445 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004447 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004448 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449}
4450
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004451/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4452/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4453/// we can simplify this expression to "cond ? C : D or B".
4454static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4455 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004456 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004457 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004458 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004459 return 0;
4460
Chris Lattnera6a474d2008-11-16 04:26:55 +00004461 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004462 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004464 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, B);
4466 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004467 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004468 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004469 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004470 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004471 return 0;
4472}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004473
Chris Lattner69d4ced2008-11-16 05:20:07 +00004474/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4475Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4476 ICmpInst *LHS, ICmpInst *RHS) {
4477 Value *Val, *Val2;
4478 ConstantInt *LHSCst, *RHSCst;
4479 ICmpInst::Predicate LHSCC, RHSCC;
4480
4481 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4482 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4483 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4484 return 0;
4485
4486 // From here on, we only handle:
4487 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4488 if (Val != Val2) return 0;
4489
4490 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4491 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4492 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4493 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4494 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4495 return 0;
4496
4497 // We can't fold (ugt x, C) | (sgt x, C2).
4498 if (!PredicatesFoldable(LHSCC, RHSCC))
4499 return 0;
4500
4501 // Ensure that the larger constant is on the RHS.
4502 bool ShouldSwap;
4503 if (ICmpInst::isSignedPredicate(LHSCC) ||
4504 (ICmpInst::isEquality(LHSCC) &&
4505 ICmpInst::isSignedPredicate(RHSCC)))
4506 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4507 else
4508 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4509
4510 if (ShouldSwap) {
4511 std::swap(LHS, RHS);
4512 std::swap(LHSCst, RHSCst);
4513 std::swap(LHSCC, RHSCC);
4514 }
4515
4516 // At this point, we know we have have two icmp instructions
4517 // comparing a value against two constants and or'ing the result
4518 // together. Because of the above check, we know that we only have
4519 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4520 // FoldICmpLogical check above), that the two constants are not
4521 // equal.
4522 assert(LHSCst != RHSCst && "Compares not folded above?");
4523
4524 switch (LHSCC) {
4525 default: assert(0 && "Unknown integer condition code!");
4526 case ICmpInst::ICMP_EQ:
4527 switch (RHSCC) {
4528 default: assert(0 && "Unknown integer condition code!");
4529 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004530 if (LHSCst == SubOne(RHSCst, Context)) {
4531 // (X == 13 | X == 14) -> X-13 <u 2
4532 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004533 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4534 Val->getName()+".off");
4535 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004536 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004537 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004538 }
4539 break; // (X == 13 | X == 15) -> no change
4540 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4541 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4542 break;
4543 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4544 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4545 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4546 return ReplaceInstUsesWith(I, RHS);
4547 }
4548 break;
4549 case ICmpInst::ICMP_NE:
4550 switch (RHSCC) {
4551 default: assert(0 && "Unknown integer condition code!");
4552 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4553 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4554 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4555 return ReplaceInstUsesWith(I, LHS);
4556 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4557 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4558 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004559 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004560 }
4561 break;
4562 case ICmpInst::ICMP_ULT:
4563 switch (RHSCC) {
4564 default: assert(0 && "Unknown integer condition code!");
4565 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4566 break;
4567 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4568 // If RHSCst is [us]MAXINT, it is always false. Not handling
4569 // this can cause overflow.
4570 if (RHSCst->isMaxValue(false))
4571 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004572 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4573 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004574 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4578 return ReplaceInstUsesWith(I, RHS);
4579 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4580 break;
4581 }
4582 break;
4583 case ICmpInst::ICMP_SLT:
4584 switch (RHSCC) {
4585 default: assert(0 && "Unknown integer condition code!");
4586 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4587 break;
4588 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4589 // If RHSCst is [us]MAXINT, it is always false. Not handling
4590 // this can cause overflow.
4591 if (RHSCst->isMaxValue(true))
4592 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004593 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4594 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004595 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4598 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4599 return ReplaceInstUsesWith(I, RHS);
4600 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_UGT:
4605 switch (RHSCC) {
4606 default: assert(0 && "Unknown integer condition code!");
4607 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4608 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004614 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4616 break;
4617 }
4618 break;
4619 case ICmpInst::ICMP_SGT:
4620 switch (RHSCC) {
4621 default: assert(0 && "Unknown integer condition code!");
4622 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4623 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4624 return ReplaceInstUsesWith(I, LHS);
4625 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4626 break;
4627 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4628 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004629 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004630 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4631 break;
4632 }
4633 break;
4634 }
4635 return 0;
4636}
4637
Bill Wendlinga698a472008-12-01 08:23:25 +00004638/// FoldOrWithConstants - This helper function folds:
4639///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004640/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004641///
4642/// into:
4643///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004644/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004645///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004646/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004647Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004648 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004649 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4650 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004651
Bill Wendling286a0542008-12-02 06:24:20 +00004652 Value *V1 = 0;
4653 ConstantInt *CI2 = 0;
4654 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004655
Bill Wendling29976b92008-12-02 06:18:11 +00004656 APInt Xor = CI1->getValue() ^ CI2->getValue();
4657 if (!Xor.isAllOnesValue()) return 0;
4658
Bill Wendling286a0542008-12-02 06:24:20 +00004659 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004660 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004661 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4662 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004663 }
4664
4665 return 0;
4666}
4667
Chris Lattner7e708292002-06-25 16:13:24 +00004668Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004669 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004671
Chris Lattner42593e62007-03-24 23:56:43 +00004672 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004673 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004674
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004675 // or X, X = X
4676 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004677 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004678
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004679 // See if we can simplify any instructions used by the instruction whose sole
4680 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004681 if (SimplifyDemandedInstructionBits(I))
4682 return &I;
4683 if (isa<VectorType>(I.getType())) {
4684 if (isa<ConstantAggregateZero>(Op1)) {
4685 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4686 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4687 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4688 return ReplaceInstUsesWith(I, I.getOperand(1));
4689 }
Chris Lattner42593e62007-03-24 23:56:43 +00004690 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004691
Chris Lattner3f5b8772002-05-06 16:14:14 +00004692 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004693 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004694 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004695 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4696 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004697 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004698 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004699 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004701 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004702 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004703
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004704 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4705 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004706 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004707 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004708 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004709 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004710 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004711 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004712
4713 // Try to fold constant and into select arguments.
4714 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004715 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004716 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004717 if (isa<PHINode>(Op0))
4718 if (Instruction *NV = FoldOpIntoPhi(I))
4719 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004720 }
4721
Chris Lattner4f637d42006-01-06 17:59:59 +00004722 Value *A = 0, *B = 0;
4723 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004724
4725 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4726 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4727 return ReplaceInstUsesWith(I, Op1);
4728 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4729 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4730 return ReplaceInstUsesWith(I, Op0);
4731
Chris Lattner6423d4c2006-07-10 20:25:24 +00004732 // (A | B) | C and A | (B | C) -> bswap if possible.
4733 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004734 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004735 match(Op1, m_Or(m_Value(), m_Value())) ||
4736 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4737 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004738 if (Instruction *BSwap = MatchBSwap(I))
4739 return BSwap;
4740 }
4741
Chris Lattner6e4c6492005-05-09 04:58:36 +00004742 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4743 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004744 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004745 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004746 InsertNewInstBefore(NOr, I);
4747 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004748 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004749 }
4750
4751 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4752 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004753 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004754 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004755 InsertNewInstBefore(NOr, I);
4756 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004757 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004758 }
4759
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004760 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004761 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004762 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4763 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004764 Value *V1 = 0, *V2 = 0, *V3 = 0;
4765 C1 = dyn_cast<ConstantInt>(C);
4766 C2 = dyn_cast<ConstantInt>(D);
4767 if (C1 && C2) { // (A & C1)|(B & C2)
4768 // If we have: ((V + N) & C1) | (V & C2)
4769 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4770 // replace with V+N.
4771 if (C1->getValue() == ~C2->getValue()) {
4772 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4773 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4774 // Add commutes, try both ways.
4775 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4776 return ReplaceInstUsesWith(I, A);
4777 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4778 return ReplaceInstUsesWith(I, A);
4779 }
4780 // Or commutes, try both ways.
4781 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4782 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4783 // Add commutes, try both ways.
4784 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4785 return ReplaceInstUsesWith(I, B);
4786 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4787 return ReplaceInstUsesWith(I, B);
4788 }
4789 }
Chris Lattner044e5332007-04-08 08:01:49 +00004790 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004791 }
4792
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004793 // Check to see if we have any common things being and'ed. If so, find the
4794 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004795 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4796 if (A == B) // (A & C)|(A & D) == A & (C|D)
4797 V1 = A, V2 = C, V3 = D;
4798 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4799 V1 = A, V2 = B, V3 = C;
4800 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4801 V1 = C, V2 = A, V3 = D;
4802 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4803 V1 = C, V2 = A, V3 = B;
4804
4805 if (V1) {
4806 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4808 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004809 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004810 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004811
Dan Gohman1975d032008-10-30 20:40:10 +00004812 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004813 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4814 return Match;
4815 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4816 return Match;
4817 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4818 return Match;
4819 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4820 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004821
Bill Wendlingb01865c2008-11-30 13:52:49 +00004822 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004823 if ((match(C, m_Not(m_Specific(D))) &&
4824 match(B, m_Not(m_Specific(A)))))
4825 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004826 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004827 if ((match(A, m_Not(m_Specific(D))) &&
4828 match(B, m_Not(m_Specific(C)))))
4829 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004830 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004831 if ((match(C, m_Not(m_Specific(B))) &&
4832 match(D, m_Not(m_Specific(A)))))
4833 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004834 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004835 if ((match(A, m_Not(m_Specific(B))) &&
4836 match(D, m_Not(m_Specific(C)))))
4837 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004838 }
Chris Lattnere511b742006-11-14 07:46:50 +00004839
4840 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004841 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4842 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4843 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004844 SI0->getOperand(1) == SI1->getOperand(1) &&
4845 (SI0->hasOneUse() || SI1->hasOneUse())) {
4846 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004847 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004848 SI1->getOperand(0),
4849 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004850 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004851 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004852 }
4853 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004854
Bill Wendlingb3833d12008-12-01 01:07:11 +00004855 // ((A|B)&1)|(B&-2) -> (A&1) | B
4856 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4857 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004858 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004859 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004860 }
4861 // (B&-2)|((A|B)&1) -> (A&1) | B
4862 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4863 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004864 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004865 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004866 }
4867
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004868 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4869 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004870 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004871 } else {
4872 A = 0;
4873 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004874 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004875 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4876 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004877 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004878
Misha Brukmancb6267b2004-07-30 12:50:08 +00004879 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004880 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004881 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004882 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004883 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004884 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004885 }
Chris Lattnera2881962003-02-18 19:28:33 +00004886
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4888 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004889 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004890 return R;
4891
Chris Lattner69d4ced2008-11-16 05:20:07 +00004892 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4893 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4894 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004895 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004896
4897 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004898 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004899 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004900 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004901 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4902 !isa<ICmpInst>(Op1C->getOperand(0))) {
4903 const Type *SrcTy = Op0C->getOperand(0)->getType();
4904 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4905 // Only do this if the casts both really cause code to be
4906 // generated.
4907 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4908 I.getType(), TD) &&
4909 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4910 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004911 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004912 Op1C->getOperand(0),
4913 I.getName());
4914 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004915 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004916 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004917 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918 }
Chris Lattner99c65742007-10-24 05:38:08 +00004919 }
4920
4921
4922 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4923 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4924 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4925 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004926 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004927 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004928 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4929 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4930 // If either of the constants are nans, then the whole thing returns
4931 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004932 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004933 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004934
4935 // Otherwise, no need to compare the two constants, compare the
4936 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004937 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4938 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004939 }
Evan Cheng40300622008-10-14 18:44:08 +00004940 } else {
4941 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4942 FCmpInst::Predicate Op0CC, Op1CC;
4943 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4944 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4945 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4946 // Swap RHS operands to match LHS.
4947 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4948 std::swap(Op1LHS, Op1RHS);
4949 }
4950 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4951 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4952 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004953 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4954 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004955 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4956 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004957 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004958 else if (Op0CC == FCmpInst::FCMP_FALSE)
4959 return ReplaceInstUsesWith(I, Op1);
4960 else if (Op1CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, Op0);
4962 bool Op0Ordered;
4963 bool Op1Ordered;
4964 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4965 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4966 if (Op0Ordered == Op1Ordered) {
4967 // If both are ordered or unordered, return a new fcmp with
4968 // or'ed predicates.
4969 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004970 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004971 if (Instruction *I = dyn_cast<Instruction>(RV))
4972 return I;
4973 // Otherwise, it's a constant boolean value...
4974 return ReplaceInstUsesWith(I, RV);
4975 }
4976 }
4977 }
4978 }
Chris Lattner99c65742007-10-24 05:38:08 +00004979 }
4980 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004981
Chris Lattner7e708292002-06-25 16:13:24 +00004982 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004983}
4984
Dan Gohman844731a2008-05-13 00:00:25 +00004985namespace {
4986
Chris Lattnerc317d392004-02-16 01:20:27 +00004987// XorSelf - Implements: X ^ X --> 0
4988struct XorSelf {
4989 Value *RHS;
4990 XorSelf(Value *rhs) : RHS(rhs) {}
4991 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4992 Instruction *apply(BinaryOperator &Xor) const {
4993 return &Xor;
4994 }
4995};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004996
Dan Gohman844731a2008-05-13 00:00:25 +00004997}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004998
Chris Lattner7e708292002-06-25 16:13:24 +00004999Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005000 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005002
Evan Chengd34af782008-03-25 20:07:13 +00005003 if (isa<UndefValue>(Op1)) {
5004 if (isa<UndefValue>(Op0))
5005 // Handle undef ^ undef -> 0 special case. This is a common
5006 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005007 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005008 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005009 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005010
Chris Lattnerc317d392004-02-16 01:20:27 +00005011 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005012 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005013 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005014 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005015 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005016
5017 // See if we can simplify any instructions used by the instruction whose sole
5018 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005019 if (SimplifyDemandedInstructionBits(I))
5020 return &I;
5021 if (isa<VectorType>(I.getType()))
5022 if (isa<ConstantAggregateZero>(Op1))
5023 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005024
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005025 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005026 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5028 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5029 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5030 if (Op0I->getOpcode() == Instruction::And ||
5031 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005032 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5033 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005034 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005035 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005036 Op0I->getOperand(1)->getName()+".not");
5037 InsertNewInstBefore(NotY, I);
5038 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005039 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005040 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005041 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005042 }
5043 }
5044 }
5045 }
5046
5047
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005048 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005049 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005050 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005051 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005052 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005054
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005055 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005056 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005057 FCI->getOperand(0), FCI->getOperand(1));
5058 }
5059
Nick Lewycky517e1f52008-05-31 19:01:33 +00005060 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5061 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5062 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5063 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5064 Instruction::CastOps Opcode = Op0C->getOpcode();
5065 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005066 if (RHS == Context->getConstantExprCast(Opcode,
5067 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005068 Op0C->getDestTy())) {
5069 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005070 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005071 CI->getOpcode(), CI->getInversePredicate(),
5072 CI->getOperand(0), CI->getOperand(1)), I);
5073 NewCI->takeName(CI);
5074 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5075 }
5076 }
5077 }
5078 }
5079 }
5080
Reid Spencere4d87aa2006-12-23 06:05:41 +00005081 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005082 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005083 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5084 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005085 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5086 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5087 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005088 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005089 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005090
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005091 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005092 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005093 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005094 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005095 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005096 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005097 Context->getConstantExprSub(NegOp0CI,
5098 Context->getConstantInt(I.getType(), 1)),
5099 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005100 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005101 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005102 Constant *C =
5103 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005105
Chris Lattner7c4049c2004-01-12 19:35:11 +00005106 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005107 } else if (Op0I->getOpcode() == Instruction::Or) {
5108 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005109 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005110 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005111 // Anything in both C1 and C2 is known to be zero, remove it from
5112 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005113 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5114 NewRHS = Context->getConstantExprAnd(NewRHS,
5115 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005116 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005117 I.setOperand(0, Op0I->getOperand(0));
5118 I.setOperand(1, NewRHS);
5119 return &I;
5120 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005121 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005122 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005123 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005124
5125 // Try to fold constant and into select arguments.
5126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005128 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005129 if (isa<PHINode>(Op0))
5130 if (Instruction *NV = FoldOpIntoPhi(I))
5131 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005132 }
5133
Owen Andersond672ecb2009-07-03 00:17:18 +00005134 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005135 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005136 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005137
Owen Andersond672ecb2009-07-03 00:17:18 +00005138 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005139 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005140 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005141
Chris Lattner318bf792007-03-18 22:51:34 +00005142
5143 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5144 if (Op1I) {
5145 Value *A, *B;
5146 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5147 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005148 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005149 I.swapOperands();
5150 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005151 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005152 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005153 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005154 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005155 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5156 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5157 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5158 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005159 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005160 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005161 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005162 std::swap(A, B);
5163 }
Chris Lattner318bf792007-03-18 22:51:34 +00005164 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005165 I.swapOperands(); // Simplified below.
5166 std::swap(Op0, Op1);
5167 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005168 }
Chris Lattner318bf792007-03-18 22:51:34 +00005169 }
5170
5171 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5172 if (Op0I) {
5173 Value *A, *B;
5174 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5175 if (A == Op1) // (B|A)^B == (A|B)^B
5176 std::swap(A, B);
5177 if (B == Op1) { // (A|B)^B == A & ~B
5178 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005179 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5180 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005181 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005182 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5183 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5184 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5185 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005186 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5187 if (A == Op1) // (A&B)^A -> (B&A)^A
5188 std::swap(A, B);
5189 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005190 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005191 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5193 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005194 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005195 }
Chris Lattner318bf792007-03-18 22:51:34 +00005196 }
5197
5198 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5199 if (Op0I && Op1I && Op0I->isShift() &&
5200 Op0I->getOpcode() == Op1I->getOpcode() &&
5201 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5202 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5203 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005205 Op1I->getOperand(0),
5206 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005208 Op1I->getOperand(1));
5209 }
5210
5211 if (Op0I && Op1I) {
5212 Value *A, *B, *C, *D;
5213 // (A & B)^(A | B) -> A ^ B
5214 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5215 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5216 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005217 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005218 }
5219 // (A | B)^(A & B) -> A ^ B
5220 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5221 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5222 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005224 }
5225
5226 // (A & B)^(C & D)
5227 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5228 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5229 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5230 // (X & Y)^(X & Y) -> (Y^Z) & X
5231 Value *X = 0, *Y = 0, *Z = 0;
5232 if (A == C)
5233 X = A, Y = B, Z = D;
5234 else if (A == D)
5235 X = A, Y = B, Z = C;
5236 else if (B == C)
5237 X = B, Y = A, Z = D;
5238 else if (B == D)
5239 X = B, Y = A, Z = C;
5240
5241 if (X) {
5242 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005243 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5244 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005245 }
5246 }
5247 }
5248
Reid Spencere4d87aa2006-12-23 06:05:41 +00005249 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5250 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005251 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005252 return R;
5253
Chris Lattner6fc205f2006-05-05 06:39:07 +00005254 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005255 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005256 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005257 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5258 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005259 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005260 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005261 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5262 I.getType(), TD) &&
5263 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5264 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005265 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005266 Op1C->getOperand(0),
5267 I.getName());
5268 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005269 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005270 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005271 }
Chris Lattner99c65742007-10-24 05:38:08 +00005272 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005273
Chris Lattner7e708292002-06-25 16:13:24 +00005274 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005275}
5276
Owen Andersond672ecb2009-07-03 00:17:18 +00005277static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005278 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005279 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005280}
Chris Lattnera96879a2004-09-29 17:40:11 +00005281
Dan Gohman6de29f82009-06-15 22:12:54 +00005282static bool HasAddOverflow(ConstantInt *Result,
5283 ConstantInt *In1, ConstantInt *In2,
5284 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005285 if (IsSigned)
5286 if (In2->getValue().isNegative())
5287 return Result->getValue().sgt(In1->getValue());
5288 else
5289 return Result->getValue().slt(In1->getValue());
5290 else
5291 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005292}
5293
Dan Gohman6de29f82009-06-15 22:12:54 +00005294/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005295/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005296static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005297 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005298 bool IsSigned = false) {
5299 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005300
Dan Gohman6de29f82009-06-15 22:12:54 +00005301 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5302 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005303 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5304 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5305 ExtractElement(In1, Idx, Context),
5306 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005307 IsSigned))
5308 return true;
5309 }
5310 return false;
5311 }
5312
5313 return HasAddOverflow(cast<ConstantInt>(Result),
5314 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5315 IsSigned);
5316}
5317
5318static bool HasSubOverflow(ConstantInt *Result,
5319 ConstantInt *In1, ConstantInt *In2,
5320 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005321 if (IsSigned)
5322 if (In2->getValue().isNegative())
5323 return Result->getValue().slt(In1->getValue());
5324 else
5325 return Result->getValue().sgt(In1->getValue());
5326 else
5327 return Result->getValue().ugt(In1->getValue());
5328}
5329
Dan Gohman6de29f82009-06-15 22:12:54 +00005330/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5331/// overflowed for this type.
5332static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005333 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005334 bool IsSigned = false) {
5335 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005336
5337 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5338 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005339 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5340 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5341 ExtractElement(In1, Idx, Context),
5342 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005343 IsSigned))
5344 return true;
5345 }
5346 return false;
5347 }
5348
5349 return HasSubOverflow(cast<ConstantInt>(Result),
5350 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5351 IsSigned);
5352}
5353
Chris Lattner574da9b2005-01-13 20:14:25 +00005354/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5355/// code necessary to compute the offset from the base pointer (without adding
5356/// in the base pointer). Return the result as a signed integer of intptr size.
5357static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5358 TargetData &TD = IC.getTargetData();
5359 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005361 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005362 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005363
5364 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005365 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005366 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005367
Gabor Greif177dd3f2008-06-12 21:37:33 +00005368 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5369 ++i, ++GTI) {
5370 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005371 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005372 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5373 if (OpC->isZero()) continue;
5374
5375 // Handle a struct index, which adds its field offset to the pointer.
5376 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5377 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5378
5379 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005380 Result =
5381 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005382 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005383 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005384 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005385 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005386 GEP->getName()+".offs"), I);
5387 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005388 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005389
Owen Andersond672ecb2009-07-03 00:17:18 +00005390 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5391 Constant *OC =
5392 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5393 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005394 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005395 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005396 else {
5397 // Emit an add instruction.
5398 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005399 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005400 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005401 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005402 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005403 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005404 // Convert to correct type.
5405 if (Op->getType() != IntPtrTy) {
5406 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005407 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005409 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5410 true,
5411 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 }
5413 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005414 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005416 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005417 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005418 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 GEP->getName()+".idx"), I);
5420 }
5421
5422 // Emit an add instruction.
5423 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005424 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 cast<Constant>(Result));
5426 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005427 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005428 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005429 }
5430 return Result;
5431}
5432
Chris Lattner10c0d912008-04-22 02:53:33 +00005433
5434/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5435/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5436/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5437/// complex, and scales are involved. The above expression would also be legal
5438/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5439/// later form is less amenable to optimization though, and we are allowed to
5440/// generate the first by knowing that pointer arithmetic doesn't overflow.
5441///
5442/// If we can't emit an optimized form for this expression, this returns null.
5443///
5444static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5445 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005446 TargetData &TD = IC.getTargetData();
5447 gep_type_iterator GTI = gep_type_begin(GEP);
5448
5449 // Check to see if this gep only has a single variable index. If so, and if
5450 // any constant indices are a multiple of its scale, then we can compute this
5451 // in terms of the scale of the variable index. For example, if the GEP
5452 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5453 // because the expression will cross zero at the same point.
5454 unsigned i, e = GEP->getNumOperands();
5455 int64_t Offset = 0;
5456 for (i = 1; i != e; ++i, ++GTI) {
5457 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5458 // Compute the aggregate offset of constant indices.
5459 if (CI->isZero()) continue;
5460
5461 // Handle a struct index, which adds its field offset to the pointer.
5462 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5463 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5464 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005465 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005466 Offset += Size*CI->getSExtValue();
5467 }
5468 } else {
5469 // Found our variable index.
5470 break;
5471 }
5472 }
5473
5474 // If there are no variable indices, we must have a constant offset, just
5475 // evaluate it the general way.
5476 if (i == e) return 0;
5477
5478 Value *VariableIdx = GEP->getOperand(i);
5479 // Determine the scale factor of the variable element. For example, this is
5480 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005481 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005482
5483 // Verify that there are no other variable indices. If so, emit the hard way.
5484 for (++i, ++GTI; i != e; ++i, ++GTI) {
5485 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5486 if (!CI) return 0;
5487
5488 // Compute the aggregate offset of constant indices.
5489 if (CI->isZero()) continue;
5490
5491 // Handle a struct index, which adds its field offset to the pointer.
5492 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5493 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5494 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005495 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005496 Offset += Size*CI->getSExtValue();
5497 }
5498 }
5499
5500 // Okay, we know we have a single variable index, which must be a
5501 // pointer/array/vector index. If there is no offset, life is simple, return
5502 // the index.
5503 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5504 if (Offset == 0) {
5505 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5506 // we don't need to bother extending: the extension won't affect where the
5507 // computation crosses zero.
5508 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5509 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5510 VariableIdx->getNameStart(), &I);
5511 return VariableIdx;
5512 }
5513
5514 // Otherwise, there is an index. The computation we will do will be modulo
5515 // the pointer size, so get it.
5516 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5517
5518 Offset &= PtrSizeMask;
5519 VariableScale &= PtrSizeMask;
5520
5521 // To do this transformation, any constant index must be a multiple of the
5522 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5523 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5524 // multiple of the variable scale.
5525 int64_t NewOffs = Offset / (int64_t)VariableScale;
5526 if (Offset != NewOffs*(int64_t)VariableScale)
5527 return 0;
5528
5529 // Okay, we can do this evaluation. Start by converting the index to intptr.
5530 const Type *IntPtrTy = TD.getIntPtrType();
5531 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005532 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005533 true /*SExt*/,
5534 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005535 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005536 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005537}
5538
5539
Reid Spencere4d87aa2006-12-23 06:05:41 +00005540/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005541/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5543 ICmpInst::Predicate Cond,
5544 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005545 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005546
Chris Lattner10c0d912008-04-22 02:53:33 +00005547 // Look through bitcasts.
5548 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005550
Chris Lattner574da9b2005-01-13 20:14:25 +00005551 Value *PtrBase = GEPLHS->getOperand(0);
5552 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005553 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005554 // This transformation (ignoring the base and scales) is valid because we
5555 // know pointers can't overflow. See if we can output an optimized form.
5556 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5557
5558 // If not, synthesize the offset the hard way.
5559 if (Offset == 0)
5560 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005561 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005562 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005563 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005564 // If the base pointers are different, but the indices are the same, just
5565 // compare the base pointer.
5566 if (PtrBase != GEPRHS->getOperand(0)) {
5567 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005568 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005569 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005570 if (IndicesTheSame)
5571 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5572 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5573 IndicesTheSame = false;
5574 break;
5575 }
5576
5577 // If all indices are the same, just compare the base pointers.
5578 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005579 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005580 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005581
5582 // Otherwise, the base pointers are different and the indices are
5583 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005584 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005585 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005586
Chris Lattnere9d782b2005-01-13 22:25:21 +00005587 // If one of the GEPs has all zero indices, recurse.
5588 bool AllZeros = true;
5589 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5590 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5591 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5592 AllZeros = false;
5593 break;
5594 }
5595 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005596 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5597 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005598
5599 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005600 AllZeros = true;
5601 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5602 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5603 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5604 AllZeros = false;
5605 break;
5606 }
5607 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005609
Chris Lattner4401c9c2005-01-14 00:20:05 +00005610 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5611 // If the GEPs only differ by one index, compare it.
5612 unsigned NumDifferences = 0; // Keep track of # differences.
5613 unsigned DiffOperand = 0; // The operand that differs.
5614 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5615 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005616 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5617 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005618 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005619 NumDifferences = 2;
5620 break;
5621 } else {
5622 if (NumDifferences++) break;
5623 DiffOperand = i;
5624 }
5625 }
5626
5627 if (NumDifferences == 0) // SAME GEP?
5628 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005629 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005630 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005631
Chris Lattner4401c9c2005-01-14 00:20:05 +00005632 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005633 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5634 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005636 return new ICmpInst(*Context,
5637 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 }
5639 }
5640
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005642 // the result to fold to a constant!
5643 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5644 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5645 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5646 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5647 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005648 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005649 }
5650 }
5651 return 0;
5652}
5653
Chris Lattnera5406232008-05-19 20:18:56 +00005654/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5655///
5656Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5657 Instruction *LHSI,
5658 Constant *RHSC) {
5659 if (!isa<ConstantFP>(RHSC)) return 0;
5660 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5661
5662 // Get the width of the mantissa. We don't want to hack on conversions that
5663 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005664 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005665 if (MantissaWidth == -1) return 0; // Unknown.
5666
5667 // Check to see that the input is converted from an integer type that is small
5668 // enough that preserves all bits. TODO: check here for "known" sign bits.
5669 // 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 +00005670 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005671
5672 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005673 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5674 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005675 ++InputSize;
5676
5677 // If the conversion would lose info, don't hack on this.
5678 if ((int)InputSize > MantissaWidth)
5679 return 0;
5680
5681 // Otherwise, we can potentially simplify the comparison. We know that it
5682 // will always come through as an integer value and we know the constant is
5683 // not a NAN (it would have been previously simplified).
5684 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5685
5686 ICmpInst::Predicate Pred;
5687 switch (I.getPredicate()) {
5688 default: assert(0 && "Unexpected predicate!");
5689 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005690 case FCmpInst::FCMP_OEQ:
5691 Pred = ICmpInst::ICMP_EQ;
5692 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005693 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005694 case FCmpInst::FCMP_OGT:
5695 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5696 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005697 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 case FCmpInst::FCMP_OGE:
5699 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5700 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005701 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005702 case FCmpInst::FCMP_OLT:
5703 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5704 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005705 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005706 case FCmpInst::FCMP_OLE:
5707 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5708 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005709 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005710 case FCmpInst::FCMP_ONE:
5711 Pred = ICmpInst::ICMP_NE;
5712 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005713 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005714 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005715 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005716 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005717 }
5718
5719 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5720
5721 // Now we know that the APFloat is a normal number, zero or inf.
5722
Chris Lattner85162782008-05-20 03:50:52 +00005723 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005724 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005725 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005726
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005727 if (!LHSUnsigned) {
5728 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5729 // and large values.
5730 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5731 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5732 APFloat::rmNearestTiesToEven);
5733 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5734 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5735 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005736 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5737 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005738 }
5739 } else {
5740 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5741 // +INF and large values.
5742 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5743 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5744 APFloat::rmNearestTiesToEven);
5745 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5746 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5747 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005748 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5749 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 }
Chris Lattnera5406232008-05-19 20:18:56 +00005751 }
5752
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005753 if (!LHSUnsigned) {
5754 // See if the RHS value is < SignedMin.
5755 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5756 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5757 APFloat::rmNearestTiesToEven);
5758 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5759 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5760 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005761 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5762 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005763 }
Chris Lattnera5406232008-05-19 20:18:56 +00005764 }
5765
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005766 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5767 // [0, UMAX], but it may still be fractional. See if it is fractional by
5768 // casting the FP value to the integer value and back, checking for equality.
5769 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005770 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005771 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5772 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005773 if (!RHS.isZero()) {
5774 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005775 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5776 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005777 if (!Equal) {
5778 // If we had a comparison against a fractional value, we have to adjust
5779 // the compare predicate and sometimes the value. RHSC is rounded towards
5780 // zero at this point.
5781 switch (Pred) {
5782 default: assert(0 && "Unexpected integer comparison!");
5783 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005784 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005785 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005786 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005787 case ICmpInst::ICMP_ULE:
5788 // (float)int <= 4.4 --> int <= 4
5789 // (float)int <= -4.4 --> false
5790 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005791 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005792 break;
5793 case ICmpInst::ICMP_SLE:
5794 // (float)int <= 4.4 --> int <= 4
5795 // (float)int <= -4.4 --> int < -4
5796 if (RHS.isNegative())
5797 Pred = ICmpInst::ICMP_SLT;
5798 break;
5799 case ICmpInst::ICMP_ULT:
5800 // (float)int < -4.4 --> false
5801 // (float)int < 4.4 --> int <= 4
5802 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005803 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 Pred = ICmpInst::ICMP_ULE;
5805 break;
5806 case ICmpInst::ICMP_SLT:
5807 // (float)int < -4.4 --> int < -4
5808 // (float)int < 4.4 --> int <= 4
5809 if (!RHS.isNegative())
5810 Pred = ICmpInst::ICMP_SLE;
5811 break;
5812 case ICmpInst::ICMP_UGT:
5813 // (float)int > 4.4 --> int > 4
5814 // (float)int > -4.4 --> true
5815 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005816 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 break;
5818 case ICmpInst::ICMP_SGT:
5819 // (float)int > 4.4 --> int > 4
5820 // (float)int > -4.4 --> int >= -4
5821 if (RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SGE;
5823 break;
5824 case ICmpInst::ICMP_UGE:
5825 // (float)int >= -4.4 --> true
5826 // (float)int >= 4.4 --> int > 4
5827 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005828 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005829 Pred = ICmpInst::ICMP_UGT;
5830 break;
5831 case ICmpInst::ICMP_SGE:
5832 // (float)int >= -4.4 --> int >= -4
5833 // (float)int >= 4.4 --> int > 4
5834 if (!RHS.isNegative())
5835 Pred = ICmpInst::ICMP_SGT;
5836 break;
5837 }
Chris Lattnera5406232008-05-19 20:18:56 +00005838 }
5839 }
5840
5841 // Lower this FP comparison into an appropriate integer version of the
5842 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005843 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005844}
5845
Reid Spencere4d87aa2006-12-23 06:05:41 +00005846Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5847 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005849
Chris Lattner58e97462007-01-14 19:42:17 +00005850 // Fold trivial predicates.
5851 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005852 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005853 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005854 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005855
5856 // Simplify 'fcmp pred X, X'
5857 if (Op0 == Op1) {
5858 switch (I.getPredicate()) {
5859 default: assert(0 && "Unknown predicate!");
5860 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5861 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5862 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005863 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005864 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5865 case FCmpInst::FCMP_OLT: // True if ordered and less than
5866 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005867 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005868
5869 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5870 case FCmpInst::FCMP_ULT: // True if unordered or less than
5871 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5872 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5873 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5874 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005875 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005876 return &I;
5877
5878 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5879 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5880 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5881 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5882 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5883 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005884 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005885 return &I;
5886 }
5887 }
5888
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005890 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005891
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 // Handle fcmp with constant RHS
5893 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005894 // If the constant is a nan, see if we can fold the comparison based on it.
5895 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5896 if (CFP->getValueAPF().isNaN()) {
5897 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005898 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005899 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5900 "Comparison must be either ordered or unordered!");
5901 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005902 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005903 }
5904 }
5905
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5907 switch (LHSI->getOpcode()) {
5908 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005909 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5910 // block. If in the same block, we're encouraging jump threading. If
5911 // not, we are just pessimizing the code by making an i1 phi.
5912 if (LHSI->getParent() == I.getParent())
5913 if (Instruction *NV = FoldOpIntoPhi(I))
5914 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005915 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005916 case Instruction::SIToFP:
5917 case Instruction::UIToFP:
5918 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5919 return NV;
5920 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 case Instruction::Select:
5922 // If either operand of the select is a constant, we can fold the
5923 // comparison into the select arms, which will cause one to be
5924 // constant folded and the select turned into a bitwise or.
5925 Value *Op1 = 0, *Op2 = 0;
5926 if (LHSI->hasOneUse()) {
5927 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5928 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005929 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005931 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 LHSI->getOperand(2), RHSC,
5933 I.getName()), I);
5934 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005936 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005938 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005939 LHSI->getOperand(1), RHSC,
5940 I.getName()), I);
5941 }
5942 }
5943
5944 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005945 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 break;
5947 }
5948 }
5949
5950 return Changed ? &I : 0;
5951}
5952
5953Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5954 bool Changed = SimplifyCompare(I);
5955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5956 const Type *Ty = Op0->getType();
5957
5958 // icmp X, X
5959 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005960 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005961 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962
5963 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005964 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005965
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005967 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005968 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5969 isa<ConstantPointerNull>(Op0)) &&
5970 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005971 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005972 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005973 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005974
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005976 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 switch (I.getPredicate()) {
5978 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005979 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005980 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005981 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005982 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005983 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005984 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005985 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005986
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005988 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005989 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005990 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005991 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005992 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005993 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005994 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005995 case ICmpInst::ICMP_SGT:
5996 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005997 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5999 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6000 InsertNewInstBefore(Not, I);
6001 return BinaryOperator::CreateAnd(Not, Op0);
6002 }
6003 case ICmpInst::ICMP_UGE:
6004 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6005 // FALL THROUGH
6006 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006007 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006008 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006009 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006010 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 case ICmpInst::ICMP_SGE:
6012 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6013 // FALL THROUGH
6014 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6015 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6016 InsertNewInstBefore(Not, I);
6017 return BinaryOperator::CreateOr(Not, Op0);
6018 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006019 }
Chris Lattner8b170942002-08-09 23:47:40 +00006020 }
6021
Dan Gohman1c8491e2009-04-25 17:12:48 +00006022 unsigned BitWidth = 0;
6023 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006024 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6025 else if (Ty->isIntOrIntVector())
6026 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006027
6028 bool isSignBit = false;
6029
Dan Gohman81b28ce2008-09-16 18:46:06 +00006030 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006031 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006032 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006033
Chris Lattnerb6566012008-01-05 01:18:20 +00006034 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6035 if (I.isEquality() && CI->isNullValue() &&
6036 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6037 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006038 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006039 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006040
Dan Gohman81b28ce2008-09-16 18:46:06 +00006041 // If we have an icmp le or icmp ge instruction, turn it into the
6042 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6043 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006044 switch (I.getPredicate()) {
6045 default: break;
6046 case ICmpInst::ICMP_ULE:
6047 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006048 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006049 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6050 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006051 case ICmpInst::ICMP_SLE:
6052 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006053 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006054 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6055 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006056 case ICmpInst::ICMP_UGE:
6057 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006058 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006059 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6060 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006061 case ICmpInst::ICMP_SGE:
6062 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006063 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006064 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6065 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006066 }
6067
Chris Lattner183661e2008-07-11 05:40:05 +00006068 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006069 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006070 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6072 }
6073
6074 // See if we can fold the comparison based on range information we can get
6075 // by checking whether bits are known to be zero or one in the input.
6076 if (BitWidth != 0) {
6077 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6078 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6079
6080 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006081 isSignBit ? APInt::getSignBit(BitWidth)
6082 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006083 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006084 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006085 if (SimplifyDemandedBits(I.getOperandUse(1),
6086 APInt::getAllOnesValue(BitWidth),
6087 Op1KnownZero, Op1KnownOne, 0))
6088 return &I;
6089
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006090 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006091 // in. Compute the Min, Max and RHS values based on the known bits. For the
6092 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006093 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6094 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6095 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6096 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097 Op0Min, Op0Max);
6098 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6099 Op1Min, Op1Max);
6100 } else {
6101 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6102 Op0Min, Op0Max);
6103 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6104 Op1Min, Op1Max);
6105 }
6106
Chris Lattner183661e2008-07-11 05:40:05 +00006107 // If Min and Max are known to be the same, then SimplifyDemandedBits
6108 // figured out that the LHS is a constant. Just constant fold this now so
6109 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006111 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006112 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006114 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006115 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116
Chris Lattner183661e2008-07-11 05:40:05 +00006117 // Based on the range information we know about the LHS, see if we can
6118 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00006120 default: assert(0 && "Unknown icmp opcode!");
6121 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006123 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006124 break;
6125 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006127 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006128 break;
6129 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006131 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006133 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006135 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006138 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6139 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140
6141 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6142 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006144 Context->getConstantIntAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 }
Chris Lattner84dff672008-07-11 05:08:55 +00006146 break;
6147 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006149 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006151 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152
6153 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(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 (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159
6160 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6161 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006163 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 }
Chris Lattner84dff672008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006168 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006170 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6174 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006175 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6176 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 case ICmpInst::ICMP_SGT:
6180 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006181 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006183 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6190 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 }
6192 break;
6193 case ICmpInst::ICMP_SGE:
6194 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6195 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006196 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006198 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 break;
6200 case ICmpInst::ICMP_SLE:
6201 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6202 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006203 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006205 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 break;
6207 case ICmpInst::ICMP_UGE:
6208 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6209 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006210 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006212 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 break;
6214 case ICmpInst::ICMP_ULE:
6215 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6216 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006217 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006219 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006220 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006221 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222
6223 // Turn a signed comparison into an unsigned one if both operands
6224 // are known to have the same sign.
6225 if (I.isSignedPredicate() &&
6226 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6227 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006228 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006229 }
6230
6231 // Test if the ICmpInst instruction is used exclusively by a select as
6232 // part of a minimum or maximum operation. If so, refrain from doing
6233 // any other folding. This helps out other analyses which understand
6234 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6235 // and CodeGen. And in this case, at least one of the comparison
6236 // operands has at least one user besides the compare (the select),
6237 // which would often largely negate the benefit of folding anyway.
6238 if (I.hasOneUse())
6239 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6240 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6241 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6242 return 0;
6243
6244 // See if we are doing a comparison between a constant and an instruction that
6245 // can be folded into the comparison.
6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006247 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006248 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006250 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006251 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6252 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006253 }
6254
Chris Lattner01deb9d2007-04-03 17:43:25 +00006255 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006256 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6257 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6258 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006259 case Instruction::GetElementPtr:
6260 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006262 bool isAllZeros = true;
6263 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6264 if (!isa<Constant>(LHSI->getOperand(i)) ||
6265 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6266 isAllZeros = false;
6267 break;
6268 }
6269 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006270 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006271 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006272 }
6273 break;
6274
Chris Lattner6970b662005-04-23 15:31:55 +00006275 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006276 // Only fold icmp into the PHI if the phi and fcmp are in the same
6277 // block. If in the same block, we're encouraging jump threading. If
6278 // not, we are just pessimizing the code by making an i1 phi.
6279 if (LHSI->getParent() == I.getParent())
6280 if (Instruction *NV = FoldOpIntoPhi(I))
6281 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006282 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006283 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006284 // If either operand of the select is a constant, we can fold the
6285 // comparison into the select arms, which will cause one to be
6286 // constant folded and the select turned into a bitwise or.
6287 Value *Op1 = 0, *Op2 = 0;
6288 if (LHSI->hasOneUse()) {
6289 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6290 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006291 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006293 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 LHSI->getOperand(2), RHSC,
6295 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006296 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6297 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006298 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006299 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006300 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 LHSI->getOperand(1), RHSC,
6302 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006303 }
6304 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006305
Chris Lattner6970b662005-04-23 15:31:55 +00006306 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006307 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006308 break;
6309 }
Chris Lattner4802d902007-04-06 18:57:34 +00006310 case Instruction::Malloc:
6311 // If we have (malloc != null), and if the malloc has a single use, we
6312 // can assume it is successful and remove the malloc.
6313 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6314 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006315 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006316 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006317 }
6318 break;
6319 }
Chris Lattner6970b662005-04-23 15:31:55 +00006320 }
6321
Reid Spencere4d87aa2006-12-23 06:05:41 +00006322 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006323 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006325 return NI;
6326 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6328 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006329 return NI;
6330
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006332 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6333 // now.
6334 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6335 if (isa<PointerType>(Op0->getType()) &&
6336 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006337 // We keep moving the cast from the left operand over to the right
6338 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006339 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006340
Chris Lattner57d86372007-01-06 01:45:59 +00006341 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6342 // so eliminate it as well.
6343 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6344 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006345
Chris Lattnerde90b762003-11-03 04:25:02 +00006346 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006347 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006348 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006349 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006350 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006352 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006353 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006354 }
Owen Anderson333c4002009-07-09 23:48:35 +00006355 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006356 }
Chris Lattner57d86372007-01-06 01:45:59 +00006357 }
6358
6359 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006361 // This comes up when you have code like
6362 // int X = A < B;
6363 // if (X) ...
6364 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006365 // with a constant or another cast from the same type.
6366 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006367 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006368 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006369 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006370
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006371 // See if it's the same type of instruction on the left and right.
6372 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6373 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006374 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006375 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006376 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006377 default: break;
6378 case Instruction::Add:
6379 case Instruction::Sub:
6380 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006381 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006382 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006383 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006384 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6385 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6386 if (CI->getValue().isSignBit()) {
6387 ICmpInst::Predicate Pred = I.isSignedPredicate()
6388 ? I.getUnsignedPredicate()
6389 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006390 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006391 Op1I->getOperand(0));
6392 }
6393
6394 if (CI->getValue().isMaxSignedValue()) {
6395 ICmpInst::Predicate Pred = I.isSignedPredicate()
6396 ? I.getUnsignedPredicate()
6397 : I.getSignedPredicate();
6398 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006399 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006400 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006401 }
6402 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006403 break;
6404 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006405 if (!I.isEquality())
6406 break;
6407
Nick Lewycky5d52c452008-08-21 05:56:10 +00006408 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6409 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6410 // Mask = -1 >> count-trailing-zeros(Cst).
6411 if (!CI->isZero() && !CI->isOne()) {
6412 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006413 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006414 APInt::getLowBitsSet(AP.getBitWidth(),
6415 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006416 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006417 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6418 Mask);
6419 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6420 Mask);
6421 InsertNewInstBefore(And1, I);
6422 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006423 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006424 }
6425 }
6426 break;
6427 }
6428 }
6429 }
6430 }
6431
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006432 // ~x < ~y --> y < x
6433 { Value *A, *B;
6434 if (match(Op0, m_Not(m_Value(A))) &&
6435 match(Op1, m_Not(m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006436 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006437 }
6438
Chris Lattner65b72ba2006-09-18 04:22:48 +00006439 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006440 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006441
6442 // -x == -y --> x == y
6443 if (match(Op0, m_Neg(m_Value(A))) &&
6444 match(Op1, m_Neg(m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006445 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006446
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006447 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6448 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6449 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006450 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006451 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006452 }
6453
6454 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6455 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006456 ConstantInt *C1, *C2;
6457 if (match(B, m_ConstantInt(C1)) &&
6458 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006459 Constant *NC =
6460 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006461 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006462 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006463 InsertNewInstBefore(Xor, I));
6464 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465
6466 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006467 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6468 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6469 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6470 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006471 }
6472 }
6473
6474 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6475 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006476 // A == (A^B) -> B == 0
6477 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006478 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006479 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006480 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006481
6482 // (A-B) == A -> B == 0
6483 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006484 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006485 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006486
6487 // A == (A-B) -> B == 0
6488 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Owen Anderson333c4002009-07-09 23:48:35 +00006489 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006490 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006491
Chris Lattner9c2328e2006-11-14 06:06:06 +00006492 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6493 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6494 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6495 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6496 Value *X = 0, *Y = 0, *Z = 0;
6497
6498 if (A == C) {
6499 X = B; Y = D; Z = A;
6500 } else if (A == D) {
6501 X = B; Y = C; Z = A;
6502 } else if (B == C) {
6503 X = A; Y = D; Z = B;
6504 } else if (B == D) {
6505 X = A; Y = C; Z = B;
6506 }
6507
6508 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006509 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6510 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006511 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006512 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006513 return &I;
6514 }
6515 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006516 }
Chris Lattner7e708292002-06-25 16:13:24 +00006517 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006518}
6519
Chris Lattner562ef782007-06-20 23:46:26 +00006520
6521/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6522/// and CmpRHS are both known to be integer constants.
6523Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6524 ConstantInt *DivRHS) {
6525 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6526 const APInt &CmpRHSV = CmpRHS->getValue();
6527
6528 // FIXME: If the operand types don't match the type of the divide
6529 // then don't attempt this transform. The code below doesn't have the
6530 // logic to deal with a signed divide and an unsigned compare (and
6531 // vice versa). This is because (x /s C1) <s C2 produces different
6532 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6533 // (x /u C1) <u C2. Simply casting the operands and result won't
6534 // work. :( The if statement below tests that condition and bails
6535 // if it finds it.
6536 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6537 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6538 return 0;
6539 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006541 if (DivIsSigned && DivRHS->isAllOnesValue())
6542 return 0; // The overflow computation also screws up here
6543 if (DivRHS->isOne())
6544 return 0; // Not worth bothering, and eliminates some funny cases
6545 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006546
6547 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6548 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6549 // C2 (CI). By solving for X we can turn this into a range check
6550 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006551 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006552
6553 // Determine if the product overflows by seeing if the product is
6554 // not equal to the divide. Make sure we do the same kind of divide
6555 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006556 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6557 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006558
6559 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006560 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006561
Chris Lattner1dbfd482007-06-21 18:11:19 +00006562 // Figure out the interval that is being checked. For example, a comparison
6563 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6564 // Compute this interval based on the constants involved and the signedness of
6565 // the compare/divide. This computes a half-open interval, keeping track of
6566 // whether either value in the interval overflows. After analysis each
6567 // overflow variable is set to 0 if it's corresponding bound variable is valid
6568 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6569 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006570 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571
Chris Lattner562ef782007-06-20 23:46:26 +00006572 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006574 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 HiOverflow = LoOverflow = ProdOV;
6576 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006577 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006578 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006579 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006581 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6582 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006583 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006584 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006585 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6586 HiOverflow = LoOverflow = ProdOV;
6587 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006588 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006589 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006591 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006592 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6593 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006594 ConstantInt* DivNeg =
6595 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6596 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006597 true) ? -1 : 0;
6598 }
Chris Lattner562ef782007-06-20 23:46:26 +00006599 }
Dan Gohman76491272008-02-13 22:09:18 +00006600 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006601 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006603 LoBound = AddOne(DivRHS, Context);
6604 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6606 HiOverflow = 1; // [INTMIN+1, overflow)
6607 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6608 }
Dan Gohman76491272008-02-13 22:09:18 +00006609 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006610 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006611 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006613 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 LoOverflow = AddWithOverflow(LoBound, HiBound,
6615 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006616 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006617 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6618 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006619 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006621 }
6622
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 // Dividing by a negative swaps the condition. LT <-> GT
6624 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006625 }
6626
6627 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006629 default: assert(0 && "Unhandled icmp opcode!");
6630 case ICmpInst::ICMP_EQ:
6631 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006632 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006633 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006634 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006635 ICmpInst::ICMP_UGE, X, LoBound);
6636 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006637 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006638 ICmpInst::ICMP_ULT, X, HiBound);
6639 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006641 case ICmpInst::ICMP_NE:
6642 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006643 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006644 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006645 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006646 ICmpInst::ICMP_ULT, X, LoBound);
6647 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006648 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006649 ICmpInst::ICMP_UGE, X, HiBound);
6650 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006652 case ICmpInst::ICMP_ULT:
6653 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006655 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006657 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006658 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006659 case ICmpInst::ICMP_UGT:
6660 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006662 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006663 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006664 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006665 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006667 else
Owen Anderson333c4002009-07-09 23:48:35 +00006668 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006669 }
6670}
6671
6672
Chris Lattner01deb9d2007-04-03 17:43:25 +00006673/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6674///
6675Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6676 Instruction *LHSI,
6677 ConstantInt *RHS) {
6678 const APInt &RHSV = RHS->getValue();
6679
6680 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006681 case Instruction::Trunc:
6682 if (ICI.isEquality() && LHSI->hasOneUse()) {
6683 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6684 // of the high bits truncated out of x are known.
6685 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6686 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6687 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6688 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6689 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6690
6691 // If all the high bits are known, we can do this xform.
6692 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6693 // Pull in the high bits from known-ones set.
6694 APInt NewRHS(RHS->getValue());
6695 NewRHS.zext(SrcBits);
6696 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006697 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006698 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006699 }
6700 }
6701 break;
6702
Duncan Sands0091bf22007-04-04 06:42:45 +00006703 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006704 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6705 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6706 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006707 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6708 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006709 Value *CompareVal = LHSI->getOperand(0);
6710
6711 // If the sign bit of the XorCST is not set, there is no change to
6712 // the operation, just stop using the Xor.
6713 if (!XorCST->getValue().isNegative()) {
6714 ICI.setOperand(0, CompareVal);
6715 AddToWorkList(LHSI);
6716 return &ICI;
6717 }
6718
6719 // Was the old condition true if the operand is positive?
6720 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6721
6722 // If so, the new one isn't.
6723 isTrueIfPositive ^= true;
6724
6725 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006726 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006727 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006728 else
Owen Anderson333c4002009-07-09 23:48:35 +00006729 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006730 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006731 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006732
6733 if (LHSI->hasOneUse()) {
6734 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6735 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6736 const APInt &SignBit = XorCST->getValue();
6737 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6738 ? ICI.getUnsignedPredicate()
6739 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006740 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006741 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006742 }
6743
6744 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006745 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006746 const APInt &NotSignBit = XorCST->getValue();
6747 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6748 ? ICI.getUnsignedPredicate()
6749 : ICI.getSignedPredicate();
6750 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006751 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006752 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006753 }
6754 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 }
6756 break;
6757 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6758 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6759 LHSI->getOperand(0)->hasOneUse()) {
6760 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6761
6762 // If the LHS is an AND of a truncating cast, we can widen the
6763 // and/compare to be the input width without changing the value
6764 // produced, eliminating a cast.
6765 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6766 // We can do this transformation if either the AND constant does not
6767 // have its sign bit set or if it is an equality comparison.
6768 // Extending a relational comparison when we're checking the sign
6769 // bit would not work.
6770 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006771 (ICI.isEquality() ||
6772 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 uint32_t BitWidth =
6774 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6775 APInt NewCST = AndCST->getValue();
6776 NewCST.zext(BitWidth);
6777 APInt NewCI = RHSV;
6778 NewCI.zext(BitWidth);
6779 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006780 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006781 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006783 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006784 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006785 }
6786 }
6787
6788 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6789 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6790 // happens a LOT in code produced by the C front-end, for bitfield
6791 // access.
6792 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6793 if (Shift && !Shift->isShift())
6794 Shift = 0;
6795
6796 ConstantInt *ShAmt;
6797 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6798 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6799 const Type *AndTy = AndCST->getType(); // Type of the and.
6800
6801 // We can fold this as long as we can't shift unknown bits
6802 // into the mask. This can only happen with signed shift
6803 // rights, as they sign-extend.
6804 if (ShAmt) {
6805 bool CanFold = Shift->isLogicalShift();
6806 if (!CanFold) {
6807 // To test for the bad case of the signed shr, see if any
6808 // of the bits shifted in could be tested after the mask.
6809 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6810 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6811
6812 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6813 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6814 AndCST->getValue()) == 0)
6815 CanFold = true;
6816 }
6817
6818 if (CanFold) {
6819 Constant *NewCst;
6820 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006821 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006822 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006823 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006824
6825 // Check to see if we are shifting out any of the bits being
6826 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006827 if (Context->getConstantExpr(Shift->getOpcode(),
6828 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829 // If we shifted bits out, the fold is not going to work out.
6830 // As a special case, check to see if this means that the
6831 // result is always true or false now.
6832 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006833 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006835 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 } else {
6837 ICI.setOperand(1, NewCst);
6838 Constant *NewAndCST;
6839 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006840 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006842 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 LHSI->setOperand(1, NewAndCST);
6844 LHSI->setOperand(0, Shift->getOperand(0));
6845 AddToWorkList(Shift); // Shift is dead.
6846 AddUsesToWorkList(ICI);
6847 return &ICI;
6848 }
6849 }
6850 }
6851
6852 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6853 // preferable because it allows the C<<Y expression to be hoisted out
6854 // of a loop if Y is invariant and X is not.
6855 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006856 ICI.isEquality() && !Shift->isArithmeticShift() &&
6857 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 // Compute C << Y.
6859 Value *NS;
6860 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006861 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 Shift->getOperand(1), "tmp");
6863 } else {
6864 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006865 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 Shift->getOperand(1), "tmp");
6867 }
6868 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6869
6870 // Compute X & (C << Y).
6871 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006872 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 InsertNewInstBefore(NewAnd, ICI);
6874
6875 ICI.setOperand(0, NewAnd);
6876 return &ICI;
6877 }
6878 }
6879 break;
6880
Chris Lattnera0141b92007-07-15 20:42:37 +00006881 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6882 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6883 if (!ShAmt) break;
6884
6885 uint32_t TypeBits = RHSV.getBitWidth();
6886
6887 // Check that the shift amount is in range. If not, don't perform
6888 // undefined shifts. When the shift is visited it will be
6889 // simplified.
6890 if (ShAmt->uge(TypeBits))
6891 break;
6892
6893 if (ICI.isEquality()) {
6894 // If we are comparing against bits always shifted out, the
6895 // comparison cannot succeed.
6896 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006897 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6898 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006899 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6900 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006901 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006902 return ReplaceInstUsesWith(ICI, Cst);
6903 }
6904
6905 if (LHSI->hasOneUse()) {
6906 // Otherwise strength reduce the shift into an and.
6907 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6908 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006909 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6910 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911
Chris Lattnera0141b92007-07-15 20:42:37 +00006912 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006913 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006914 Mask, LHSI->getName()+".mask");
6915 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006916 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006917 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006918 }
6919 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006920
6921 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6922 bool TrueIfSigned = false;
6923 if (LHSI->hasOneUse() &&
6924 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6925 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006926 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006927 (TypeBits-ShAmt->getZExtValue()-1));
6928 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006929 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 Mask, LHSI->getName()+".mask");
6931 Value *And = InsertNewInstBefore(AndI, ICI);
6932
Owen Anderson333c4002009-07-09 23:48:35 +00006933 return new ICmpInst(*Context,
6934 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006935 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006936 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006937 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006938 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006939
6940 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006942 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006944 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006945
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006946 // Check that the shift amount is in range. If not, don't perform
6947 // undefined shifts. When the shift is visited it will be
6948 // simplified.
6949 uint32_t TypeBits = RHSV.getBitWidth();
6950 if (ShAmt->uge(TypeBits))
6951 break;
6952
6953 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006954
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006955 // If we are comparing against bits always shifted out, the
6956 // comparison cannot succeed.
6957 APInt Comp = RHSV << ShAmtVal;
6958 if (LHSI->getOpcode() == Instruction::LShr)
6959 Comp = Comp.lshr(ShAmtVal);
6960 else
6961 Comp = Comp.ashr(ShAmtVal);
6962
6963 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6964 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006965 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006966 return ReplaceInstUsesWith(ICI, Cst);
6967 }
6968
6969 // Otherwise, check to see if the bits shifted out are known to be zero.
6970 // If so, we can compare against the unshifted value:
6971 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006972 if (LHSI->hasOneUse() &&
6973 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006975 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006976 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006978
Evan Chengf30752c2008-04-23 00:38:06 +00006979 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006980 // Otherwise strength reduce the shift into an and.
6981 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006982 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006983
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006985 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006986 Mask, LHSI->getName()+".mask");
6987 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006988 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006989 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990 }
6991 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006992 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006993
6994 case Instruction::SDiv:
6995 case Instruction::UDiv:
6996 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6997 // Fold this div into the comparison, producing a range check.
6998 // Determine, based on the divide type, what the range is being
6999 // checked. If there is an overflow on the low or high side, remember
7000 // it, otherwise compute the range [low, hi) bounding the new value.
7001 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007002 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7003 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7004 DivRHS))
7005 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007006 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007007
7008 case Instruction::Add:
7009 // Fold: icmp pred (add, X, C1), C2
7010
7011 if (!ICI.isEquality()) {
7012 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7013 if (!LHSC) break;
7014 const APInt &LHSV = LHSC->getValue();
7015
7016 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7017 .subtract(LHSV);
7018
7019 if (ICI.isSignedPredicate()) {
7020 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007021 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007022 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007023 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007024 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007025 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007026 }
7027 } else {
7028 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007029 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007030 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007031 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007032 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007033 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007034 }
7035 }
7036 }
7037 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 }
7039
7040 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7041 if (ICI.isEquality()) {
7042 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7043
7044 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7045 // the second operand is a constant, simplify a bit.
7046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7047 switch (BO->getOpcode()) {
7048 case Instruction::SRem:
7049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7050 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7051 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7052 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7053 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007054 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 BO->getName());
7056 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007057 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007058 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007059 }
7060 }
7061 break;
7062 case Instruction::Add:
7063 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7064 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007066 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007067 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 } else if (RHSV == 0) {
7069 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7070 // efficiently invertible, or if the add has just this one use.
7071 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7072
Owen Andersond672ecb2009-07-03 00:17:18 +00007073 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007074 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007075 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007076 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007078 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 InsertNewInstBefore(Neg, ICI);
7080 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007081 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007082 }
7083 }
7084 break;
7085 case Instruction::Xor:
7086 // For the xor case, we can xor two constants together, eliminating
7087 // the explicit xor.
7088 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007089 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007090 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007091
7092 // FALLTHROUGH
7093 case Instruction::Sub:
7094 // Replace (([sub|xor] A, B) != 0) with (A != B)
7095 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007096 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 BO->getOperand(1));
7098 break;
7099
7100 case Instruction::Or:
7101 // If bits are being or'd in that are not present in the constant we
7102 // are comparing against, then the comparison could never succeed!
7103 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007104 Constant *NotCI = Context->getConstantExprNot(RHS);
7105 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7106 return ReplaceInstUsesWith(ICI,
7107 Context->getConstantInt(Type::Int1Ty,
7108 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 }
7110 break;
7111
7112 case Instruction::And:
7113 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7114 // If bits are being compared against that are and'd out, then the
7115 // comparison can never succeed!
7116 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007117 return ReplaceInstUsesWith(ICI,
7118 Context->getConstantInt(Type::Int1Ty,
7119 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7122 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007123 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007125 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126
7127 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007128 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007129 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007130 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007131 ICmpInst::Predicate pred = isICMP_NE ?
7132 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007133 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007134 }
7135
7136 // ((X & ~7) == 0) --> X < 8
7137 if (RHSV == 0 && isHighOnes(BOC)) {
7138 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007139 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007140 ICmpInst::Predicate pred = isICMP_NE ?
7141 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007142 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007143 }
7144 }
7145 default: break;
7146 }
7147 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7148 // Handle icmp {eq|ne} <intrinsic>, intcst.
7149 if (II->getIntrinsicID() == Intrinsic::bswap) {
7150 AddToWorkList(II);
7151 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007152 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 return &ICI;
7154 }
7155 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 }
7157 return 0;
7158}
7159
7160/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7161/// We only handle extending casts so far.
7162///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007163Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7164 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007165 Value *LHSCIOp = LHSCI->getOperand(0);
7166 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007167 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007168 Value *RHSCIOp;
7169
Chris Lattner8c756c12007-05-05 22:41:33 +00007170 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7171 // integer type is the same size as the pointer type.
7172 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7173 getTargetData().getPointerSizeInBits() ==
7174 cast<IntegerType>(DestTy)->getBitWidth()) {
7175 Value *RHSOp = 0;
7176 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007177 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007178 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7179 RHSOp = RHSC->getOperand(0);
7180 // If the pointer types don't match, insert a bitcast.
7181 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007182 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007183 }
7184
7185 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007186 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007187 }
7188
7189 // The code below only handles extension cast instructions, so far.
7190 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 if (LHSCI->getOpcode() != Instruction::ZExt &&
7192 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007193 return 0;
7194
Reid Spencere4d87aa2006-12-23 06:05:41 +00007195 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7196 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007197
Reid Spencere4d87aa2006-12-23 06:05:41 +00007198 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007199 // Not an extension from the same type?
7200 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007201 if (RHSCIOp->getType() != LHSCIOp->getType())
7202 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007203
Nick Lewycky4189a532008-01-28 03:48:02 +00007204 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007205 // and the other is a zext), then we can't handle this.
7206 if (CI->getOpcode() != LHSCI->getOpcode())
7207 return 0;
7208
Nick Lewycky4189a532008-01-28 03:48:02 +00007209 // Deal with equality cases early.
7210 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007211 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007212
7213 // A signed comparison of sign extended values simplifies into a
7214 // signed comparison.
7215 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007216 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007217
7218 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007219 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007220 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007221
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 // If we aren't dealing with a constant on the RHS, exit early
7223 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7224 if (!CI)
7225 return 0;
7226
7227 // Compute the constant that would happen if we truncated to SrcTy then
7228 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007229 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7230 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7231 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232
7233 // If the re-extended constant didn't change...
7234 if (Res2 == CI) {
7235 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7236 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007237 // %A = sext i16 %X to i32
7238 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007240 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241 // because %A may have negative value.
7242 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007243 // However, we allow this when the compare is EQ/NE, because they are
7244 // signless.
7245 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007246 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007247 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007248 }
7249
7250 // The re-extended constant changed so the constant cannot be represented
7251 // in the shorter type. Consequently, we cannot emit a simple comparison.
7252
7253 // First, handle some easy cases. We know the result cannot be equal at this
7254 // point so handle the ICI.isEquality() cases
7255 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007256 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007258 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259
7260 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7261 // should have been folded away previously and not enter in here.
7262 Value *Result;
7263 if (isSignedCmp) {
7264 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007265 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007266 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007268 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007269 } else {
7270 // We're performing an unsigned comparison.
7271 if (isSignedExt) {
7272 // We're performing an unsigned comp with a sign extended value.
7273 // This is true if the input is >= 0. [aka >s -1]
Owen Andersond672ecb2009-07-03 00:17:18 +00007274 Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007275 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7276 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277 } else {
7278 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007279 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 }
7281 }
7282
7283 // Finally, return the value computed.
7284 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007285 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007287
7288 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7289 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7290 "ICmp should be folded!");
7291 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007292 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Chris Lattnerf2991842008-07-11 04:09:09 +00007293 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007294}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007295
Reid Spencer832254e2007-02-02 02:16:23 +00007296Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7297 return commonShiftTransforms(I);
7298}
7299
7300Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7301 return commonShiftTransforms(I);
7302}
7303
7304Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007305 if (Instruction *R = commonShiftTransforms(I))
7306 return R;
7307
7308 Value *Op0 = I.getOperand(0);
7309
7310 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7311 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7312 if (CSI->isAllOnesValue())
7313 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007314
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007315 // See if we can turn a signed shr into an unsigned shr.
7316 if (MaskedValueIsZero(Op0,
7317 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7318 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7319
7320 // Arithmetic shifting an all-sign-bit value is a no-op.
7321 unsigned NumSignBits = ComputeNumSignBits(Op0);
7322 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7323 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007324
Chris Lattner348f6652007-12-06 01:59:46 +00007325 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007326}
7327
7328Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7329 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007331
7332 // shl X, 0 == X and shr X, 0 == X
7333 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007334 if (Op1 == Context->getNullValue(Op1->getType()) ||
7335 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007336 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007337
Reid Spencere4d87aa2006-12-23 06:05:41 +00007338 if (isa<UndefValue>(Op0)) {
7339 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007340 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007341 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007342 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007343 }
7344 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007345 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7346 return ReplaceInstUsesWith(I, Op0);
7347 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007348 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007349 }
7350
Dan Gohman9004c8a2009-05-21 02:28:33 +00007351 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007352 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007353 return &I;
7354
Chris Lattner2eefe512004-04-09 19:05:30 +00007355 // Try to fold constant and into select arguments.
7356 if (isa<Constant>(Op0))
7357 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007358 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007359 return R;
7360
Reid Spencerb83eb642006-10-20 07:07:24 +00007361 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007362 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7363 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007364 return 0;
7365}
7366
Reid Spencerb83eb642006-10-20 07:07:24 +00007367Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007368 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007369 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007370
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007371 // See if we can simplify any instructions used by the instruction whose sole
7372 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007373 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007374
Dan Gohmana119de82009-06-14 23:30:43 +00007375 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7376 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007377 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007378 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007379 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007380 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007382 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007384 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007385 }
7386
7387 // ((X*C1) << C2) == (X * (C1 << C2))
7388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7389 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7390 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007391 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007392 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393
7394 // Try to fold constant and into select arguments.
7395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7397 return R;
7398 if (isa<PHINode>(Op0))
7399 if (Instruction *NV = FoldOpIntoPhi(I))
7400 return NV;
7401
Chris Lattner8999dd32007-12-22 09:07:47 +00007402 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7403 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7404 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7405 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7406 // place. Don't try to do this transformation in this case. Also, we
7407 // require that the input operand is a shift-by-constant so that we have
7408 // confidence that the shifts will get folded together. We could do this
7409 // xform in more cases, but it is unlikely to be profitable.
7410 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7411 isa<ConstantInt>(TrOp->getOperand(1))) {
7412 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007413 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007414 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007415 I.getName());
7416 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7417
7418 // For logical shifts, the truncation has the effect of making the high
7419 // part of the register be zeros. Emulate this by inserting an AND to
7420 // clear the top bits as needed. This 'and' will usually be zapped by
7421 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007422 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7423 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007424 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7425
7426 // The mask we constructed says what the trunc would do if occurring
7427 // between the shifts. We want to know the effect *after* the second
7428 // shift. We know that it is a logical shift by a constant, so adjust the
7429 // mask as appropriate.
7430 if (I.getOpcode() == Instruction::Shl)
7431 MaskV <<= Op1->getZExtValue();
7432 else {
7433 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7434 MaskV = MaskV.lshr(Op1->getZExtValue());
7435 }
7436
Owen Andersond672ecb2009-07-03 00:17:18 +00007437 Instruction *And =
7438 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7439 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007440 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7441
7442 // Return the value truncated to the interesting size.
7443 return new TruncInst(And, I.getType());
7444 }
7445 }
7446
Chris Lattner4d5542c2006-01-06 07:12:35 +00007447 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007448 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7449 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7450 Value *V1, *V2;
7451 ConstantInt *CC;
7452 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007453 default: break;
7454 case Instruction::Add:
7455 case Instruction::And:
7456 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007457 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007458 // These operators commute.
7459 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007460 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007461 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007462 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007463 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007464 Op0BO->getName());
7465 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007466 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007467 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007468 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007469 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007470 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007471 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007472 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007473 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007474
Chris Lattner150f12a2005-09-18 06:30:59 +00007475 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007476 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007477 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007478 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007479 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7480 m_ConstantInt(CC))) &&
7481 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007482 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007483 Op0BO->getOperand(0), Op1,
7484 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007485 InsertNewInstBefore(YS, I); // (Y << C)
7486 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007487 BinaryOperator::CreateAnd(V1,
7488 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 V1->getName()+".mask");
7490 InsertNewInstBefore(XM, I); // X & (CC << C)
7491
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007493 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007494 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007495
Reid Spencera07cb7d2007-02-02 14:41:37 +00007496 // FALL THROUGH.
7497 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007498 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007500 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007501 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007502 Op0BO->getOperand(1), Op1,
7503 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007504 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007505 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007507 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007508 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007510 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007512 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007513
Chris Lattner13d4ab42006-05-31 21:14:00 +00007514 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007515 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7516 match(Op0BO->getOperand(0),
7517 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007518 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007519 cast<BinaryOperator>(Op0BO->getOperand(0))
7520 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007521 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007522 Op0BO->getOperand(1), Op1,
7523 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007524 InsertNewInstBefore(YS, I); // (Y << C)
7525 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007526 BinaryOperator::CreateAnd(V1,
7527 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007528 V1->getName()+".mask");
7529 InsertNewInstBefore(XM, I); // X & (CC << C)
7530
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007531 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007532 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007533
Chris Lattner11021cb2005-09-18 05:12:10 +00007534 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007536 }
7537
7538
7539 // If the operand is an bitwise operator with a constant RHS, and the
7540 // shift is the only use, we can pull it out of the shift.
7541 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7542 bool isValid = true; // Valid only for And, Or, Xor
7543 bool highBitSet = false; // Transform if high bit of constant set?
7544
7545 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007546 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007547 case Instruction::Add:
7548 isValid = isLeftShift;
7549 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007550 case Instruction::Or:
7551 case Instruction::Xor:
7552 highBitSet = false;
7553 break;
7554 case Instruction::And:
7555 highBitSet = true;
7556 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007557 }
7558
7559 // If this is a signed shift right, and the high bit is modified
7560 // by the logical operation, do not perform the transformation.
7561 // The highBitSet boolean indicates the value of the high bit of
7562 // the constant which would cause it to be modified for this
7563 // operation.
7564 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007565 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007566 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007567
7568 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007569 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570
7571 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007572 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007573 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007574 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007575
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007576 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007577 NewRHS);
7578 }
7579 }
7580 }
7581 }
7582
Chris Lattnerad0124c2006-01-06 07:52:12 +00007583 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007584 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7585 if (ShiftOp && !ShiftOp->isShift())
7586 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007587
Reid Spencerb83eb642006-10-20 07:07:24 +00007588 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007589 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007590 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7591 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007592 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7593 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7594 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007595
Zhou Sheng4351c642007-04-02 08:20:41 +00007596 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007597
7598 const IntegerType *Ty = cast<IntegerType>(I.getType());
7599
7600 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007601 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007602 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7603 // saturates.
7604 if (AmtSum >= TypeBits) {
7605 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007606 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007607 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7608 }
7609
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007610 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007611 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007612 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7613 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007614 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007615 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007616
Chris Lattnerb87056f2007-02-05 00:57:54 +00007617 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007618 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007619 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7620 I.getOpcode() == Instruction::LShr) {
7621 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007622 if (AmtSum >= TypeBits)
7623 AmtSum = TypeBits-1;
7624
Chris Lattnerb87056f2007-02-05 00:57:54 +00007625 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007626 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007627 InsertNewInstBefore(Shift, I);
7628
Zhou Shenge9e03f62007-03-28 15:02:20 +00007629 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007630 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007631 }
7632
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 // Okay, if we get here, one shift must be left, and the other shift must be
7634 // right. See if the amounts are equal.
7635 if (ShiftAmt1 == ShiftAmt2) {
7636 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7637 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007638 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007639 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 }
7641 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7642 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007643 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007644 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 }
7646 // We can simplify ((X << C) >>s C) into a trunc + sext.
7647 // NOTE: we could do this for any C, but that would make 'unusual' integer
7648 // types. For now, just stick to ones well-supported by the code
7649 // generators.
7650 const Type *SExtType = 0;
7651 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007652 case 1 :
7653 case 8 :
7654 case 16 :
7655 case 32 :
7656 case 64 :
7657 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007658 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007659 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007660 default: break;
7661 }
7662 if (SExtType) {
7663 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7664 InsertNewInstBefore(NewTrunc, I);
7665 return new SExtInst(NewTrunc, Ty);
7666 }
7667 // Otherwise, we can't handle it yet.
7668 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007669 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007670
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007671 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007672 if (I.getOpcode() == Instruction::Shl) {
7673 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7674 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007675 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007676 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007677 InsertNewInstBefore(Shift, I);
7678
Reid Spencer55702aa2007-03-25 21:11:44 +00007679 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007680 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007681 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007682
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007683 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007684 if (I.getOpcode() == Instruction::LShr) {
7685 assert(ShiftOp->getOpcode() == Instruction::Shl);
7686 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007687 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007688 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007689
Reid Spencerd5e30f02007-03-26 17:18:58 +00007690 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007691 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007692 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693
7694 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7695 } else {
7696 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007697 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007698
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007699 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 if (I.getOpcode() == Instruction::Shl) {
7701 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7702 ShiftOp->getOpcode() == Instruction::AShr);
7703 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007704 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007705 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007706 InsertNewInstBefore(Shift, I);
7707
Reid Spencer55702aa2007-03-25 21:11:44 +00007708 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007709 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007710 }
7711
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007712 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 if (I.getOpcode() == Instruction::LShr) {
7714 assert(ShiftOp->getOpcode() == Instruction::Shl);
7715 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007716 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 InsertNewInstBefore(Shift, I);
7718
Reid Spencer68d27cf2007-03-26 23:45:51 +00007719 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007720 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 }
7722
7723 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007724 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007725 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007726 return 0;
7727}
7728
Chris Lattnera1be5662002-05-02 17:06:02 +00007729
Chris Lattnercfd65102005-10-29 04:36:15 +00007730/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7731/// expression. If so, decompose it, returning some value X, such that Val is
7732/// X*Scale+Offset.
7733///
7734static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007735 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007736 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007737 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007738 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007739 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007740 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007741 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7743 if (I->getOpcode() == Instruction::Shl) {
7744 // This is a value scaled by '1 << the shift amt'.
7745 Scale = 1U << RHS->getZExtValue();
7746 Offset = 0;
7747 return I->getOperand(0);
7748 } else if (I->getOpcode() == Instruction::Mul) {
7749 // This value is scaled by 'RHS'.
7750 Scale = RHS->getZExtValue();
7751 Offset = 0;
7752 return I->getOperand(0);
7753 } else if (I->getOpcode() == Instruction::Add) {
7754 // We have X+C. Check to see if we really have (X*C2)+C1,
7755 // where C1 is divisible by C2.
7756 unsigned SubScale;
7757 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007758 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7759 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007760 Offset += RHS->getZExtValue();
7761 Scale = SubScale;
7762 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007763 }
7764 }
7765 }
7766
7767 // Otherwise, we can't look past this.
7768 Scale = 1;
7769 Offset = 0;
7770 return Val;
7771}
7772
7773
Chris Lattnerb3f83972005-10-24 06:03:58 +00007774/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7775/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007776Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007777 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007778 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007779
Chris Lattnerb53c2382005-10-24 06:22:12 +00007780 // Remove any uses of AI that are dead.
7781 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007782
Chris Lattnerb53c2382005-10-24 06:22:12 +00007783 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7784 Instruction *User = cast<Instruction>(*UI++);
7785 if (isInstructionTriviallyDead(User)) {
7786 while (UI != E && *UI == User)
7787 ++UI; // If this instruction uses AI more than once, don't break UI.
7788
Chris Lattnerb53c2382005-10-24 06:22:12 +00007789 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007790 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007791 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007792 }
7793 }
7794
Chris Lattnerb3f83972005-10-24 06:03:58 +00007795 // Get the type really allocated and the type casted to.
7796 const Type *AllocElTy = AI.getAllocatedType();
7797 const Type *CastElTy = PTy->getElementType();
7798 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007799
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007800 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7801 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007802 if (CastElTyAlign < AllocElTyAlign) return 0;
7803
Chris Lattner39387a52005-10-24 06:35:18 +00007804 // If the allocation has multiple uses, only promote it if we are strictly
7805 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007806 // same, we open the door to infinite loops of various kinds. (A reference
7807 // from a dbg.declare doesn't count as a use for this purpose.)
7808 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7809 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007810
Duncan Sands777d2302009-05-09 07:06:46 +00007811 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7812 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007813 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007814
Chris Lattner455fcc82005-10-29 03:19:53 +00007815 // See if we can satisfy the modulus by pulling a scale out of the array
7816 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007817 unsigned ArraySizeScale;
7818 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007819 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007820 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7821 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007822
Chris Lattner455fcc82005-10-29 03:19:53 +00007823 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7824 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007825 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7826 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007827
Chris Lattner455fcc82005-10-29 03:19:53 +00007828 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7829 Value *Amt = 0;
7830 if (Scale == 1) {
7831 Amt = NumElements;
7832 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007833 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007834 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007835 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007836 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007837 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007838 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007839 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007840 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007841 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007842 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007843 }
7844
Jeff Cohen86796be2007-04-04 16:58:57 +00007845 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007846 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007847 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007848 Amt = InsertNewInstBefore(Tmp, AI);
7849 }
7850
Chris Lattnerb3f83972005-10-24 06:03:58 +00007851 AllocationInst *New;
7852 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007853 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007854 else
Chris Lattner6934a042007-02-11 01:23:03 +00007855 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007856 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007857 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007858
Dale Johannesena0a66372009-03-05 00:39:02 +00007859 // If the allocation has one real use plus a dbg.declare, just remove the
7860 // declare.
7861 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7862 EraseInstFromFunction(*DI);
7863 }
7864 // If the allocation has multiple real uses, insert a cast and change all
7865 // things that used it to use the new cast. This will also hack on CI, but it
7866 // will die soon.
7867 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007868 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007869 // New is the allocation instruction, pointer typed. AI is the original
7870 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7871 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007872 InsertNewInstBefore(NewCast, AI);
7873 AI.replaceAllUsesWith(NewCast);
7874 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007875 return ReplaceInstUsesWith(CI, New);
7876}
7877
Chris Lattner70074e02006-05-13 02:06:03 +00007878/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007879/// and return it as type Ty without inserting any new casts and without
7880/// changing the computed value. This is used by code that tries to decide
7881/// whether promoting or shrinking integer operations to wider or smaller types
7882/// will allow us to eliminate a truncate or extend.
7883///
7884/// This is a truncation operation if Ty is smaller than V->getType(), or an
7885/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007886///
7887/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7888/// should return true if trunc(V) can be computed by computing V in the smaller
7889/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7890/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7891/// efficiently truncated.
7892///
7893/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7894/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7895/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007896bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007897 unsigned CastOpc,
7898 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007899 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007900 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007901 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007902
7903 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007904 if (!I) return false;
7905
Dan Gohman6de29f82009-06-15 22:12:54 +00007906 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007907
Chris Lattner951626b2007-08-02 06:11:14 +00007908 // If this is an extension or truncate, we can often eliminate it.
7909 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7910 // If this is a cast from the destination type, we can trivially eliminate
7911 // it, and this will remove a cast overall.
7912 if (I->getOperand(0)->getType() == Ty) {
7913 // If the first operand is itself a cast, and is eliminable, do not count
7914 // this as an eliminable cast. We would prefer to eliminate those two
7915 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007916 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007917 ++NumCastsRemoved;
7918 return true;
7919 }
7920 }
7921
7922 // We can't extend or shrink something that has multiple uses: doing so would
7923 // require duplicating the instruction in general, which isn't profitable.
7924 if (!I->hasOneUse()) return false;
7925
Evan Chengf35fd542009-01-15 17:01:23 +00007926 unsigned Opc = I->getOpcode();
7927 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 case Instruction::Add:
7929 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007930 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007931 case Instruction::And:
7932 case Instruction::Or:
7933 case Instruction::Xor:
7934 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007936 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007937 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007938 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939
Chris Lattner46b96052006-11-29 07:18:39 +00007940 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007941 // If we are truncating the result of this SHL, and if it's a shift of a
7942 // constant amount, we can always perform a SHL in a smaller type.
7943 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007944 uint32_t BitWidth = Ty->getScalarSizeInBits();
7945 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007946 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007947 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007948 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007949 }
7950 break;
7951 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007952 // If this is a truncate of a logical shr, we can truncate it to a smaller
7953 // lshr iff we know that the bits we would otherwise be shifting in are
7954 // already zeros.
7955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007956 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7957 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007958 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007960 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7961 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007963 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007964 }
7965 }
Chris Lattner46b96052006-11-29 07:18:39 +00007966 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007967 case Instruction::ZExt:
7968 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007969 case Instruction::Trunc:
7970 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007971 // can safely replace it. Note that replacing it does not reduce the number
7972 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007973 if (Opc == CastOpc)
7974 return true;
7975
7976 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007977 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007978 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007979 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007980 case Instruction::Select: {
7981 SelectInst *SI = cast<SelectInst>(I);
7982 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007983 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007984 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007985 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007986 }
Chris Lattner8114b712008-06-18 04:00:49 +00007987 case Instruction::PHI: {
7988 // We can change a phi if we can change all operands.
7989 PHINode *PN = cast<PHINode>(I);
7990 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7991 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007992 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007993 return false;
7994 return true;
7995 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007996 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007997 // TODO: Can handle more cases here.
7998 break;
7999 }
8000
8001 return false;
8002}
8003
8004/// EvaluateInDifferentType - Given an expression that
8005/// CanEvaluateInDifferentType returns true for, actually insert the code to
8006/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008007Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008008 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008009 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008010 return Context->getConstantExprIntegerCast(C, Ty,
8011 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008012
8013 // Otherwise, it must be an instruction.
8014 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008015 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008016 unsigned Opc = I->getOpcode();
8017 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008018 case Instruction::Add:
8019 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008020 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008021 case Instruction::And:
8022 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008023 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008024 case Instruction::AShr:
8025 case Instruction::LShr:
8026 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008027 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008028 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008029 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008030 break;
8031 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008032 case Instruction::Trunc:
8033 case Instruction::ZExt:
8034 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008035 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008036 // just return the source. There's no need to insert it because it is not
8037 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008038 if (I->getOperand(0)->getType() == Ty)
8039 return I->getOperand(0);
8040
Chris Lattner8114b712008-06-18 04:00:49 +00008041 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008042 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008043 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008044 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008045 case Instruction::Select: {
8046 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8047 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8048 Res = SelectInst::Create(I->getOperand(0), True, False);
8049 break;
8050 }
Chris Lattner8114b712008-06-18 04:00:49 +00008051 case Instruction::PHI: {
8052 PHINode *OPN = cast<PHINode>(I);
8053 PHINode *NPN = PHINode::Create(Ty);
8054 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8055 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8056 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8057 }
8058 Res = NPN;
8059 break;
8060 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008061 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008062 // TODO: Can handle more cases here.
8063 assert(0 && "Unreachable!");
8064 break;
8065 }
8066
Chris Lattner8114b712008-06-18 04:00:49 +00008067 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008068 return InsertNewInstBefore(Res, *I);
8069}
8070
Reid Spencer3da59db2006-11-27 01:05:10 +00008071/// @brief Implement the transforms common to all CastInst visitors.
8072Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008073 Value *Src = CI.getOperand(0);
8074
Dan Gohman23d9d272007-05-11 21:10:54 +00008075 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008076 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008077 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008078 if (Instruction::CastOps opc =
8079 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8080 // The first cast (CSrc) is eliminable so we need to fix up or replace
8081 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008083 }
8084 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008085
Reid Spencer3da59db2006-11-27 01:05:10 +00008086 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008087 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8088 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8089 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008090
8091 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008092 if (isa<PHINode>(Src))
8093 if (Instruction *NV = FoldOpIntoPhi(CI))
8094 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008095
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 return 0;
8097}
8098
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099/// FindElementAtOffset - Given a type and a constant offset, determine whether
8100/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008101/// the specified offset. If so, fill them into NewIndices and return the
8102/// resultant element type, otherwise return null.
8103static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8104 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008105 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008106 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008107 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008108
8109 // Start with the index over the outer type. Note that the type size
8110 // might be zero (even if the offset isn't zero) if the indexed type
8111 // is something like [0 x {int, int}]
8112 const Type *IntPtrTy = TD->getIntPtrType();
8113 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008114 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008115 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008116 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008117
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008118 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008119 if (Offset < 0) {
8120 --FirstIdx;
8121 Offset += TySize;
8122 assert(Offset >= 0);
8123 }
8124 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8125 }
8126
Owen Andersond672ecb2009-07-03 00:17:18 +00008127 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008128
8129 // Index into the types. If we fail, set OrigBase to null.
8130 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008131 // Indexing into tail padding between struct/array elements.
8132 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008133 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008134
Chris Lattner46cd5a12009-01-09 05:44:56 +00008135 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8136 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008137 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8138 "Offset must stay within the indexed type");
8139
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008141 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008142
8143 Offset -= SL->getElementOffset(Elt);
8144 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008145 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008146 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008147 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008148 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008149 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008150 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008151 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008152 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008153 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008154 }
8155 }
8156
Chris Lattner3914f722009-01-24 01:00:13 +00008157 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008158}
8159
Chris Lattnerd3e28342007-04-27 17:44:50 +00008160/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8161Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8162 Value *Src = CI.getOperand(0);
8163
Chris Lattnerd3e28342007-04-27 17:44:50 +00008164 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008165 // If casting the result of a getelementptr instruction with no offset, turn
8166 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008167 if (GEP->hasAllZeroIndices()) {
8168 // Changing the cast operand is usually not a good idea but it is safe
8169 // here because the pointer operand is being replaced with another
8170 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008171 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008172 CI.setOperand(0, GEP->getOperand(0));
8173 return &CI;
8174 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008175
8176 // If the GEP has a single use, and the base pointer is a bitcast, and the
8177 // GEP computes a constant offset, see if we can convert these three
8178 // instructions into fewer. This typically happens with unions and other
8179 // non-type-safe code.
8180 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8181 if (GEP->hasAllConstantIndices()) {
8182 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008183 ConstantInt *OffsetV =
8184 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008185 int64_t Offset = OffsetV->getSExtValue();
8186
8187 // Get the base pointer input of the bitcast, and the type it points to.
8188 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8189 const Type *GEPIdxTy =
8190 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008191 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008192 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008193 // If we were able to index down into an element, create the GEP
8194 // and bitcast the result. This eliminates one bitcast, potentially
8195 // two.
8196 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8197 NewIndices.begin(),
8198 NewIndices.end(), "");
8199 InsertNewInstBefore(NGEP, CI);
8200 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008201
Chris Lattner46cd5a12009-01-09 05:44:56 +00008202 if (isa<BitCastInst>(CI))
8203 return new BitCastInst(NGEP, CI.getType());
8204 assert(isa<PtrToIntInst>(CI));
8205 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008206 }
8207 }
8208 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008209 }
8210
8211 return commonCastTransforms(CI);
8212}
8213
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008214/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8215/// type like i42. We don't want to introduce operations on random non-legal
8216/// integer types where they don't already exist in the code. In the future,
8217/// we should consider making this based off target-data, so that 32-bit targets
8218/// won't get i64 operations etc.
8219static bool isSafeIntegerType(const Type *Ty) {
8220 switch (Ty->getPrimitiveSizeInBits()) {
8221 case 8:
8222 case 16:
8223 case 32:
8224 case 64:
8225 return true;
8226 default:
8227 return false;
8228 }
8229}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230
Chris Lattnerc739cd62007-03-03 05:27:34 +00008231/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8232/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008233/// cases.
8234/// @brief Implement the transforms common to CastInst with integer operands
8235Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8236 if (Instruction *Result = commonCastTransforms(CI))
8237 return Result;
8238
8239 Value *Src = CI.getOperand(0);
8240 const Type *SrcTy = Src->getType();
8241 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008242 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8243 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008244
Reid Spencer3da59db2006-11-27 01:05:10 +00008245 // See if we can simplify any instructions used by the LHS whose sole
8246 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008247 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008248 return &CI;
8249
8250 // If the source isn't an instruction or has more than one use then we
8251 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008252 Instruction *SrcI = dyn_cast<Instruction>(Src);
8253 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008254 return 0;
8255
Chris Lattnerc739cd62007-03-03 05:27:34 +00008256 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008257 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008258 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008259 // Only do this if the dest type is a simple type, don't convert the
8260 // expression tree to something weird like i93 unless the source is also
8261 // strange.
Dan Gohman6de29f82009-06-15 22:12:54 +00008262 (isSafeIntegerType(DestTy->getScalarType()) ||
8263 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8264 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008265 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008266 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008267 // eliminates the cast, so it is always a win. If this is a zero-extension,
8268 // we need to do an AND to maintain the clear top-part of the computation,
8269 // so we require that the input have eliminated at least one cast. If this
8270 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008271 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008272 bool DoXForm = false;
8273 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008274 switch (CI.getOpcode()) {
8275 default:
8276 // All the others use floating point so we shouldn't actually
8277 // get here because of the check above.
8278 assert(0 && "Unknown cast type");
8279 case Instruction::Trunc:
8280 DoXForm = true;
8281 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008282 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008283 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008284 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008285 // If it's unnecessary to issue an AND to clear the high bits, it's
8286 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008287 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008288 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8289 if (MaskedValueIsZero(TryRes, Mask))
8290 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008291
8292 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008293 if (TryI->use_empty())
8294 EraseInstFromFunction(*TryI);
8295 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008296 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008297 }
Evan Chengf35fd542009-01-15 17:01:23 +00008298 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008299 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008300 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008301 // If we do not have to emit the truncate + sext pair, then it's always
8302 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008303 //
8304 // It's not safe to eliminate the trunc + sext pair if one of the
8305 // eliminated cast is a truncate. e.g.
8306 // t2 = trunc i32 t1 to i16
8307 // t3 = sext i16 t2 to i32
8308 // !=
8309 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008310 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8312 if (NumSignBits > (DestBitSize - SrcBitSize))
8313 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008314
8315 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008316 if (TryI->use_empty())
8317 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008318 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008319 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 }
Evan Chengf35fd542009-01-15 17:01:23 +00008321 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008322
8323 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008324 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8325 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008326 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8327 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008329 // Just replace this cast with the result.
8330 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331
Reid Spencer3da59db2006-11-27 01:05:10 +00008332 assert(Res->getType() == DestTy);
8333 switch (CI.getOpcode()) {
8334 default: assert(0 && "Unknown cast type!");
8335 case Instruction::Trunc:
8336 case Instruction::BitCast:
8337 // Just replace this cast with the result.
8338 return ReplaceInstUsesWith(CI, Res);
8339 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008340 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008341
8342 // If the high bits are already zero, just replace this cast with the
8343 // result.
8344 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8345 if (MaskedValueIsZero(Res, Mask))
8346 return ReplaceInstUsesWith(CI, Res);
8347
8348 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008349 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008350 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008351 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008353 case Instruction::SExt: {
8354 // If the high bits are already filled with sign bit, just replace this
8355 // cast with the result.
8356 unsigned NumSignBits = ComputeNumSignBits(Res);
8357 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008358 return ReplaceInstUsesWith(CI, Res);
8359
Reid Spencer3da59db2006-11-27 01:05:10 +00008360 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008361 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008362 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8363 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 }
8367 }
8368
8369 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8370 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8371
8372 switch (SrcI->getOpcode()) {
8373 case Instruction::Add:
8374 case Instruction::Mul:
8375 case Instruction::And:
8376 case Instruction::Or:
8377 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008378 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8380 // Don't insert two casts if they cannot be eliminated. We allow
8381 // two casts to be inserted if the sizes are the same. This could
8382 // only be converting signedness, which is a noop.
8383 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008384 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8385 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008386 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008387 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8388 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008389 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008390 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008391 }
8392 }
8393
8394 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8395 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8396 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008397 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008398 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008399 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008400 return BinaryOperator::CreateXor(New,
8401 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008402 }
8403 break;
8404 case Instruction::SDiv:
8405 case Instruction::UDiv:
8406 case Instruction::SRem:
8407 case Instruction::URem:
8408 // If we are just changing the sign, rewrite.
8409 if (DestBitSize == SrcBitSize) {
8410 // Don't insert two casts if they cannot be eliminated. We allow
8411 // two casts to be inserted if the sizes are the same. This could
8412 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008413 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8414 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008415 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8416 Op0, DestTy, *SrcI);
8417 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8418 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008419 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8421 }
8422 }
8423 break;
8424
8425 case Instruction::Shl:
8426 // Allow changing the sign of the source operand. Do not allow
8427 // changing the size of the shift, UNLESS the shift amount is a
8428 // constant. We must not change variable sized shifts to a smaller
8429 // size, because it is undefined to shift more bits out than exist
8430 // in the value.
8431 if (DestBitSize == SrcBitSize ||
8432 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008433 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8434 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008435 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8436 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008437 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008438 }
8439 break;
8440 case Instruction::AShr:
8441 // If this is a signed shr, and if all bits shifted in are about to be
8442 // truncated off, turn it into an unsigned shr to allow greater
8443 // simplifications.
8444 if (DestBitSize < SrcBitSize &&
8445 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008446 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008447 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8448 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008449 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008450 }
8451 }
8452 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008453 }
8454 return 0;
8455}
8456
Chris Lattner8a9f5712007-04-11 06:57:46 +00008457Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008458 if (Instruction *Result = commonIntCastTransforms(CI))
8459 return Result;
8460
8461 Value *Src = CI.getOperand(0);
8462 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008463 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8464 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008465
8466 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008467 if (DestBitWidth == 1 &&
8468 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008469 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008470 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008471 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008472 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008473 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008474
Chris Lattner4f9797d2009-03-24 18:15:30 +00008475 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8476 ConstantInt *ShAmtV = 0;
8477 Value *ShiftOp = 0;
8478 if (Src->hasOneUse() &&
8479 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8480 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8481
8482 // Get a mask for the bits shifting in.
8483 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8484 if (MaskedValueIsZero(ShiftOp, Mask)) {
8485 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008486 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008487
8488 // Okay, we can shrink this. Truncate the input, then return a new
8489 // shift.
8490 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008491 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008492 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008493 }
8494 }
8495
8496 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008497}
8498
Evan Chengb98a10e2008-03-24 00:21:34 +00008499/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8500/// in order to eliminate the icmp.
8501Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8502 bool DoXform) {
8503 // If we are just checking for a icmp eq of a single bit and zext'ing it
8504 // to an integer, then shift the bit to the appropriate place and then
8505 // cast to integer to avoid the comparison.
8506 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8507 const APInt &Op1CV = Op1C->getValue();
8508
8509 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8510 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8511 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8512 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8513 if (!DoXform) return ICI;
8514
8515 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008516 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008517 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008518 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008519 In->getName()+".lobit"),
8520 CI);
8521 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008522 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008523 false/*ZExt*/, "tmp", &CI);
8524
8525 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008526 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008527 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008528 In->getName()+".not"),
8529 CI);
8530 }
8531
8532 return ReplaceInstUsesWith(CI, In);
8533 }
8534
8535
8536
8537 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8538 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8539 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8540 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8541 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8542 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8543 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8544 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8545 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8546 // This only works for EQ and NE
8547 ICI->isEquality()) {
8548 // If Op1C some other power of two, convert:
8549 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8550 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8551 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8552 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8553
8554 APInt KnownZeroMask(~KnownZero);
8555 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8556 if (!DoXform) return ICI;
8557
8558 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8559 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8560 // (X&4) == 2 --> false
8561 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008562 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8563 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008564 return ReplaceInstUsesWith(CI, Res);
8565 }
8566
8567 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8568 Value *In = ICI->getOperand(0);
8569 if (ShiftAmt) {
8570 // Perform a logical shr by shiftamt.
8571 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008572 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008573 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008574 In->getName()+".lobit"), CI);
8575 }
8576
8577 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008578 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008579 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008580 InsertNewInstBefore(cast<Instruction>(In), CI);
8581 }
8582
8583 if (CI.getType() == In->getType())
8584 return ReplaceInstUsesWith(CI, In);
8585 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008586 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008587 }
8588 }
8589 }
8590
8591 return 0;
8592}
8593
Chris Lattner8a9f5712007-04-11 06:57:46 +00008594Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008595 // If one of the common conversion will work ..
8596 if (Instruction *Result = commonIntCastTransforms(CI))
8597 return Result;
8598
8599 Value *Src = CI.getOperand(0);
8600
Chris Lattnera84f47c2009-02-17 20:47:23 +00008601 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8602 // types and if the sizes are just right we can convert this into a logical
8603 // 'and' which will be much cheaper than the pair of casts.
8604 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8605 // Get the sizes of the types involved. We know that the intermediate type
8606 // will be smaller than A or C, but don't know the relation between A and C.
8607 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008608 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8609 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8610 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008611 // If we're actually extending zero bits, then if
8612 // SrcSize < DstSize: zext(a & mask)
8613 // SrcSize == DstSize: a & mask
8614 // SrcSize > DstSize: trunc(a) & mask
8615 if (SrcSize < DstSize) {
8616 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008617 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008618 Instruction *And =
8619 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8620 InsertNewInstBefore(And, CI);
8621 return new ZExtInst(And, CI.getType());
8622 } else if (SrcSize == DstSize) {
8623 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008624 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008625 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008626 } else if (SrcSize > DstSize) {
8627 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8628 InsertNewInstBefore(Trunc, CI);
8629 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008630 return BinaryOperator::CreateAnd(Trunc,
8631 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008632 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008633 }
8634 }
8635
Evan Chengb98a10e2008-03-24 00:21:34 +00008636 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8637 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008638
Evan Chengb98a10e2008-03-24 00:21:34 +00008639 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8640 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8641 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8642 // of the (zext icmp) will be transformed.
8643 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8644 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8645 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8646 (transformZExtICmp(LHS, CI, false) ||
8647 transformZExtICmp(RHS, CI, false))) {
8648 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8649 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008650 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008651 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008652 }
8653
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008654 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008655 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8656 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8657 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8658 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008659 if (TI0->getType() == CI.getType())
8660 return
8661 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008662 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008663 }
8664
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008665 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8666 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8667 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8668 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8669 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8670 And->getOperand(1) == C)
8671 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8672 Value *TI0 = TI->getOperand(0);
8673 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008674 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008675 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8676 InsertNewInstBefore(NewAnd, *And);
8677 return BinaryOperator::CreateXor(NewAnd, ZC);
8678 }
8679 }
8680
Reid Spencer3da59db2006-11-27 01:05:10 +00008681 return 0;
8682}
8683
Chris Lattner8a9f5712007-04-11 06:57:46 +00008684Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008685 if (Instruction *I = commonIntCastTransforms(CI))
8686 return I;
8687
Chris Lattner8a9f5712007-04-11 06:57:46 +00008688 Value *Src = CI.getOperand(0);
8689
Dan Gohman1975d032008-10-30 20:40:10 +00008690 // Canonicalize sign-extend from i1 to a select.
8691 if (Src->getType() == Type::Int1Ty)
8692 return SelectInst::Create(Src,
Owen Andersond672ecb2009-07-03 00:17:18 +00008693 Context->getConstantIntAllOnesValue(CI.getType()),
8694 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008695
8696 // See if the value being truncated is already sign extended. If so, just
8697 // eliminate the trunc/sext pair.
8698 if (getOpcode(Src) == Instruction::Trunc) {
8699 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008700 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8701 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8702 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008703 unsigned NumSignBits = ComputeNumSignBits(Op);
8704
8705 if (OpBits == DestBits) {
8706 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8707 // bits, it is already ready.
8708 if (NumSignBits > DestBits-MidBits)
8709 return ReplaceInstUsesWith(CI, Op);
8710 } else if (OpBits < DestBits) {
8711 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8712 // bits, just sext from i32.
8713 if (NumSignBits > OpBits-MidBits)
8714 return new SExtInst(Op, CI.getType(), "tmp");
8715 } else {
8716 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8717 // bits, just truncate to i32.
8718 if (NumSignBits > OpBits-MidBits)
8719 return new TruncInst(Op, CI.getType(), "tmp");
8720 }
8721 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008722
8723 // If the input is a shl/ashr pair of a same constant, then this is a sign
8724 // extension from a smaller value. If we could trust arbitrary bitwidth
8725 // integers, we could turn this into a truncate to the smaller bit and then
8726 // use a sext for the whole extension. Since we don't, look deeper and check
8727 // for a truncate. If the source and dest are the same type, eliminate the
8728 // trunc and extend and just do shifts. For example, turn:
8729 // %a = trunc i32 %i to i8
8730 // %b = shl i8 %a, 6
8731 // %c = ashr i8 %b, 6
8732 // %d = sext i8 %c to i32
8733 // into:
8734 // %a = shl i32 %i, 30
8735 // %d = ashr i32 %a, 30
8736 Value *A = 0;
8737 ConstantInt *BA = 0, *CA = 0;
8738 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8739 m_ConstantInt(CA))) &&
8740 BA == CA && isa<TruncInst>(A)) {
8741 Value *I = cast<TruncInst>(A)->getOperand(0);
8742 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008743 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8744 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008745 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008746 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008747 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8748 CI.getName()), CI);
8749 return BinaryOperator::CreateAShr(I, ShAmtV);
8750 }
8751 }
8752
Chris Lattnerba417832007-04-11 06:12:58 +00008753 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008754}
8755
Chris Lattnerb7530652008-01-27 05:29:54 +00008756/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8757/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008758static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008759 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008760 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008761 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008762 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8763 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008764 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008765 return 0;
8766}
8767
8768/// LookThroughFPExtensions - If this is an fp extension instruction, look
8769/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008770static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008771 if (Instruction *I = dyn_cast<Instruction>(V))
8772 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008773 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008774
8775 // If this value is a constant, return the constant in the smallest FP type
8776 // that can accurately represent it. This allows us to turn
8777 // (float)((double)X+2.0) into x+2.0f.
8778 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8779 if (CFP->getType() == Type::PPC_FP128Ty)
8780 return V; // No constant folding of this.
8781 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008782 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008783 return V;
8784 if (CFP->getType() == Type::DoubleTy)
8785 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008786 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008787 return V;
8788 // Don't try to shrink to various long double types.
8789 }
8790
8791 return V;
8792}
8793
8794Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8795 if (Instruction *I = commonCastTransforms(CI))
8796 return I;
8797
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008798 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008799 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008800 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 // many builtins (sqrt, etc).
8802 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8803 if (OpI && OpI->hasOneUse()) {
8804 switch (OpI->getOpcode()) {
8805 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008806 case Instruction::FAdd:
8807 case Instruction::FSub:
8808 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008809 case Instruction::FDiv:
8810 case Instruction::FRem:
8811 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008812 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8813 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 if (LHSTrunc->getType() != SrcTy &&
8815 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008816 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008817 // If the source types were both smaller than the destination type of
8818 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008819 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8820 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008821 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8822 CI.getType(), CI);
8823 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8824 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008825 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008826 }
8827 }
8828 break;
8829 }
8830 }
8831 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008832}
8833
8834Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8835 return commonCastTransforms(CI);
8836}
8837
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008838Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008839 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8840 if (OpI == 0)
8841 return commonCastTransforms(FI);
8842
8843 // fptoui(uitofp(X)) --> X
8844 // fptoui(sitofp(X)) --> X
8845 // This is safe if the intermediate type has enough bits in its mantissa to
8846 // accurately represent all values of X. For example, do not do this with
8847 // i64->float->i64. This is also safe for sitofp case, because any negative
8848 // 'X' value would cause an undefined result for the fptoui.
8849 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8850 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008851 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008852 OpI->getType()->getFPMantissaWidth())
8853 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008854
8855 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008856}
8857
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008858Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008859 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8860 if (OpI == 0)
8861 return commonCastTransforms(FI);
8862
8863 // fptosi(sitofp(X)) --> X
8864 // fptosi(uitofp(X)) --> X
8865 // This is safe if the intermediate type has enough bits in its mantissa to
8866 // accurately represent all values of X. For example, do not do this with
8867 // i64->float->i64. This is also safe for sitofp case, because any negative
8868 // 'X' value would cause an undefined result for the fptoui.
8869 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8870 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008871 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008872 OpI->getType()->getFPMantissaWidth())
8873 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008874
8875 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008876}
8877
8878Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8879 return commonCastTransforms(CI);
8880}
8881
8882Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8883 return commonCastTransforms(CI);
8884}
8885
Chris Lattnera0e69692009-03-24 18:35:40 +00008886Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8887 // If the destination integer type is smaller than the intptr_t type for
8888 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8889 // trunc to be exposed to other transforms. Don't do this for extending
8890 // ptrtoint's, because we don't know if the target sign or zero extends its
8891 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008892 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008893 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8894 TD->getIntPtrType(),
8895 "tmp"), CI);
8896 return new TruncInst(P, CI.getType());
8897 }
8898
Chris Lattnerd3e28342007-04-27 17:44:50 +00008899 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008900}
8901
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008902Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008903 // If the source integer type is larger than the intptr_t type for
8904 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8905 // allows the trunc to be exposed to other transforms. Don't do this for
8906 // extending inttoptr's, because we don't know if the target sign or zero
8907 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008908 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008909 TD->getPointerSizeInBits()) {
8910 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8911 TD->getIntPtrType(),
8912 "tmp"), CI);
8913 return new IntToPtrInst(P, CI.getType());
8914 }
8915
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008916 if (Instruction *I = commonCastTransforms(CI))
8917 return I;
8918
8919 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8920 if (!DestPointee->isSized()) return 0;
8921
8922 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8923 ConstantInt *Cst;
8924 Value *X;
8925 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8926 m_ConstantInt(Cst)))) {
8927 // If the source and destination operands have the same type, see if this
8928 // is a single-index GEP.
8929 if (X->getType() == CI.getType()) {
8930 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008931 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008932
8933 // Convert the constant to intptr type.
8934 APInt Offset = Cst->getValue();
8935 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8936
8937 // If Offset is evenly divisible by Size, we can do this xform.
8938 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8939 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersond672ecb2009-07-03 00:17:18 +00008940 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008941 }
8942 }
8943 // TODO: Could handle other cases, e.g. where add is indexing into field of
8944 // struct etc.
8945 } else if (CI.getOperand(0)->hasOneUse() &&
8946 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8947 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8948 // "inttoptr+GEP" instead of "add+intptr".
8949
8950 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008951 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008952
8953 // Convert the constant to intptr type.
8954 APInt Offset = Cst->getValue();
8955 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8956
8957 // If Offset is evenly divisible by Size, we can do this xform.
8958 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8959 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8960
8961 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8962 "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008963 return GetElementPtrInst::Create(P,
8964 Context->getConstantInt(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008965 }
8966 }
8967 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008968}
8969
Chris Lattnerd3e28342007-04-27 17:44:50 +00008970Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008971 // If the operands are integer typed then apply the integer transforms,
8972 // otherwise just apply the common ones.
8973 Value *Src = CI.getOperand(0);
8974 const Type *SrcTy = Src->getType();
8975 const Type *DestTy = CI.getType();
8976
Chris Lattner42a75512007-01-15 02:27:26 +00008977 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008978 if (Instruction *Result = commonIntCastTransforms(CI))
8979 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008980 } else if (isa<PointerType>(SrcTy)) {
8981 if (Instruction *I = commonPointerCastTransforms(CI))
8982 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008983 } else {
8984 if (Instruction *Result = commonCastTransforms(CI))
8985 return Result;
8986 }
8987
8988
8989 // Get rid of casts from one type to the same type. These are useless and can
8990 // be replaced by the operand.
8991 if (DestTy == Src->getType())
8992 return ReplaceInstUsesWith(CI, Src);
8993
Reid Spencer3da59db2006-11-27 01:05:10 +00008994 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008995 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8996 const Type *DstElTy = DstPTy->getElementType();
8997 const Type *SrcElTy = SrcPTy->getElementType();
8998
Nate Begeman83ad90a2008-03-31 00:22:16 +00008999 // If the address spaces don't match, don't eliminate the bitcast, which is
9000 // required for changing types.
9001 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9002 return 0;
9003
Chris Lattnerd3e28342007-04-27 17:44:50 +00009004 // If we are casting a malloc or alloca to a pointer to a type of the same
9005 // size, rewrite the allocation instruction to allocate the "right" type.
9006 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9007 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9008 return V;
9009
Chris Lattnerd717c182007-05-05 22:32:24 +00009010 // If the source and destination are pointers, and this cast is equivalent
9011 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009012 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009013 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009014 unsigned NumZeros = 0;
9015 while (SrcElTy != DstElTy &&
9016 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9017 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9018 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9019 ++NumZeros;
9020 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009021
Chris Lattnerd3e28342007-04-27 17:44:50 +00009022 // If we found a path from the src to dest, create the getelementptr now.
9023 if (SrcElTy == DstElTy) {
9024 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009025 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9026 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009027 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009028 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009029
Reid Spencer3da59db2006-11-27 01:05:10 +00009030 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9031 if (SVI->hasOneUse()) {
9032 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9033 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009034 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009035 cast<VectorType>(DestTy)->getNumElements() ==
9036 SVI->getType()->getNumElements() &&
9037 SVI->getType()->getNumElements() ==
9038 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009039 CastInst *Tmp;
9040 // If either of the operands is a cast from CI.getType(), then
9041 // evaluating the shuffle in the casted destination's type will allow
9042 // us to eliminate at least one cast.
9043 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9044 Tmp->getOperand(0)->getType() == DestTy) ||
9045 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9046 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009047 Value *LHS = InsertCastBefore(Instruction::BitCast,
9048 SVI->getOperand(0), DestTy, CI);
9049 Value *RHS = InsertCastBefore(Instruction::BitCast,
9050 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009051 // Return a new shuffle vector. Use the same element ID's, as we
9052 // know the vector types match #elts.
9053 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009054 }
9055 }
9056 }
9057 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009058 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009059}
9060
Chris Lattnere576b912004-04-09 23:46:01 +00009061/// GetSelectFoldableOperands - We want to turn code that looks like this:
9062/// %C = or %A, %B
9063/// %D = select %cond, %C, %A
9064/// into:
9065/// %C = select %cond, %B, 0
9066/// %D = or %A, %C
9067///
9068/// Assuming that the specified instruction is an operand to the select, return
9069/// a bitmask indicating which operands of this instruction are foldable if they
9070/// equal the other incoming value of the select.
9071///
9072static unsigned GetSelectFoldableOperands(Instruction *I) {
9073 switch (I->getOpcode()) {
9074 case Instruction::Add:
9075 case Instruction::Mul:
9076 case Instruction::And:
9077 case Instruction::Or:
9078 case Instruction::Xor:
9079 return 3; // Can fold through either operand.
9080 case Instruction::Sub: // Can only fold on the amount subtracted.
9081 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009082 case Instruction::LShr:
9083 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009084 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009085 default:
9086 return 0; // Cannot fold
9087 }
9088}
9089
9090/// GetSelectFoldableConstant - For the same transformation as the previous
9091/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009092static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009093 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009094 switch (I->getOpcode()) {
9095 default: assert(0 && "This cannot happen!"); abort();
9096 case Instruction::Add:
9097 case Instruction::Sub:
9098 case Instruction::Or:
9099 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009100 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009101 case Instruction::LShr:
9102 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009103 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009104 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009105 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009106 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009107 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009108 }
9109}
9110
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009111/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9112/// have the same opcode and only one use each. Try to simplify this.
9113Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9114 Instruction *FI) {
9115 if (TI->getNumOperands() == 1) {
9116 // If this is a non-volatile load or a cast from the same type,
9117 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009118 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9120 return 0;
9121 } else {
9122 return 0; // unknown unary op.
9123 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009124
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009125 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009126 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9127 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009128 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009129 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009130 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009131 }
9132
Reid Spencer832254e2007-02-02 02:16:23 +00009133 // Only handle binary operators here.
9134 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009135 return 0;
9136
9137 // Figure out if the operations have any operands in common.
9138 Value *MatchOp, *OtherOpT, *OtherOpF;
9139 bool MatchIsOpZero;
9140 if (TI->getOperand(0) == FI->getOperand(0)) {
9141 MatchOp = TI->getOperand(0);
9142 OtherOpT = TI->getOperand(1);
9143 OtherOpF = FI->getOperand(1);
9144 MatchIsOpZero = true;
9145 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9146 MatchOp = TI->getOperand(1);
9147 OtherOpT = TI->getOperand(0);
9148 OtherOpF = FI->getOperand(0);
9149 MatchIsOpZero = false;
9150 } else if (!TI->isCommutative()) {
9151 return 0;
9152 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9153 MatchOp = TI->getOperand(0);
9154 OtherOpT = TI->getOperand(1);
9155 OtherOpF = FI->getOperand(0);
9156 MatchIsOpZero = true;
9157 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9158 MatchOp = TI->getOperand(1);
9159 OtherOpT = TI->getOperand(0);
9160 OtherOpF = FI->getOperand(1);
9161 MatchIsOpZero = true;
9162 } else {
9163 return 0;
9164 }
9165
9166 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009167 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9168 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009169 InsertNewInstBefore(NewSI, SI);
9170
9171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9172 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009173 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009174 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009175 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009176 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00009177 assert(0 && "Shouldn't get here");
9178 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009179}
9180
Evan Chengde621922009-03-31 20:42:45 +00009181static bool isSelect01(Constant *C1, Constant *C2) {
9182 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9183 if (!C1I)
9184 return false;
9185 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9186 if (!C2I)
9187 return false;
9188 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9189}
9190
9191/// FoldSelectIntoOp - Try fold the select into one of the operands to
9192/// facilitate further optimization.
9193Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9194 Value *FalseVal) {
9195 // See the comment above GetSelectFoldableOperands for a description of the
9196 // transformation we are doing here.
9197 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9198 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9199 !isa<Constant>(FalseVal)) {
9200 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9201 unsigned OpToFold = 0;
9202 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9203 OpToFold = 1;
9204 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9205 OpToFold = 2;
9206 }
9207
9208 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009209 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009210 Value *OOp = TVI->getOperand(2-OpToFold);
9211 // Avoid creating select between 2 constants unless it's selecting
9212 // between 0 and 1.
9213 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9214 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9215 InsertNewInstBefore(NewSel, SI);
9216 NewSel->takeName(TVI);
9217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9218 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9219 assert(0 && "Unknown instruction!!");
9220 }
9221 }
9222 }
9223 }
9224 }
9225
9226 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9227 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9228 !isa<Constant>(TrueVal)) {
9229 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9230 unsigned OpToFold = 0;
9231 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9232 OpToFold = 1;
9233 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9234 OpToFold = 2;
9235 }
9236
9237 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009238 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009239 Value *OOp = FVI->getOperand(2-OpToFold);
9240 // Avoid creating select between 2 constants unless it's selecting
9241 // between 0 and 1.
9242 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9243 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9244 InsertNewInstBefore(NewSel, SI);
9245 NewSel->takeName(FVI);
9246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9247 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9248 assert(0 && "Unknown instruction!!");
9249 }
9250 }
9251 }
9252 }
9253 }
9254
9255 return 0;
9256}
9257
Dan Gohman81b28ce2008-09-16 18:46:06 +00009258/// visitSelectInstWithICmp - Visit a SelectInst that has an
9259/// ICmpInst as its first operand.
9260///
9261Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9262 ICmpInst *ICI) {
9263 bool Changed = false;
9264 ICmpInst::Predicate Pred = ICI->getPredicate();
9265 Value *CmpLHS = ICI->getOperand(0);
9266 Value *CmpRHS = ICI->getOperand(1);
9267 Value *TrueVal = SI.getTrueValue();
9268 Value *FalseVal = SI.getFalseValue();
9269
9270 // Check cases where the comparison is with a constant that
9271 // can be adjusted to fit the min/max idiom. We may edit ICI in
9272 // place here, so make sure the select is the only user.
9273 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009274 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009275 switch (Pred) {
9276 default: break;
9277 case ICmpInst::ICMP_ULT:
9278 case ICmpInst::ICMP_SLT: {
9279 // X < MIN ? T : F --> F
9280 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009283 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009284 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286 Pred = ICmpInst::getSwappedPredicate(Pred);
9287 CmpRHS = AdjustedRHS;
9288 std::swap(FalseVal, TrueVal);
9289 ICI->setPredicate(Pred);
9290 ICI->setOperand(1, CmpRHS);
9291 SI.setOperand(1, TrueVal);
9292 SI.setOperand(2, FalseVal);
9293 Changed = true;
9294 }
9295 break;
9296 }
9297 case ICmpInst::ICMP_UGT:
9298 case ICmpInst::ICMP_SGT: {
9299 // X > MAX ? T : F --> F
9300 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9301 return ReplaceInstUsesWith(SI, FalseVal);
9302 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009303 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009304 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9305 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9306 Pred = ICmpInst::getSwappedPredicate(Pred);
9307 CmpRHS = AdjustedRHS;
9308 std::swap(FalseVal, TrueVal);
9309 ICI->setPredicate(Pred);
9310 ICI->setOperand(1, CmpRHS);
9311 SI.setOperand(1, TrueVal);
9312 SI.setOperand(2, FalseVal);
9313 Changed = true;
9314 }
9315 break;
9316 }
9317 }
9318
Dan Gohman1975d032008-10-30 20:40:10 +00009319 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9320 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009321 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009322 if (match(TrueVal, m_ConstantInt<-1>()) &&
9323 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009324 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009325 else if (match(TrueVal, m_ConstantInt<0>()) &&
9326 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009327 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9328
Dan Gohman1975d032008-10-30 20:40:10 +00009329 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9330 // If we are just checking for a icmp eq of a single bit and zext'ing it
9331 // to an integer, then shift the bit to the appropriate place and then
9332 // cast to integer to avoid the comparison.
9333 const APInt &Op1CV = CI->getValue();
9334
9335 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9336 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9337 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009338 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009339 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009340 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009341 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009342 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9343 In->getName()+".lobit"),
9344 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009345 if (In->getType() != SI.getType())
9346 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009347 true/*SExt*/, "tmp", ICI);
9348
9349 if (Pred == ICmpInst::ICMP_SGT)
9350 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9351 In->getName()+".not"), *ICI);
9352
9353 return ReplaceInstUsesWith(SI, In);
9354 }
9355 }
9356 }
9357
Dan Gohman81b28ce2008-09-16 18:46:06 +00009358 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9359 // Transform (X == Y) ? X : Y -> Y
9360 if (Pred == ICmpInst::ICMP_EQ)
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 // Transform (X != Y) ? X : Y -> X
9363 if (Pred == ICmpInst::ICMP_NE)
9364 return ReplaceInstUsesWith(SI, TrueVal);
9365 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9366
9367 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9368 // Transform (X == Y) ? Y : X -> X
9369 if (Pred == ICmpInst::ICMP_EQ)
9370 return ReplaceInstUsesWith(SI, FalseVal);
9371 // Transform (X != Y) ? Y : X -> Y
9372 if (Pred == ICmpInst::ICMP_NE)
9373 return ReplaceInstUsesWith(SI, TrueVal);
9374 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9375 }
9376
9377 /// NOTE: if we wanted to, this is where to detect integer ABS
9378
9379 return Changed ? &SI : 0;
9380}
9381
Chris Lattner3d69f462004-03-12 05:52:32 +00009382Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009383 Value *CondVal = SI.getCondition();
9384 Value *TrueVal = SI.getTrueValue();
9385 Value *FalseVal = SI.getFalseValue();
9386
9387 // select true, X, Y -> X
9388 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009389 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009390 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009391
9392 // select C, X, X -> X
9393 if (TrueVal == FalseVal)
9394 return ReplaceInstUsesWith(SI, TrueVal);
9395
Chris Lattnere87597f2004-10-16 18:11:37 +00009396 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9397 return ReplaceInstUsesWith(SI, FalseVal);
9398 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9399 return ReplaceInstUsesWith(SI, TrueVal);
9400 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9401 if (isa<Constant>(TrueVal))
9402 return ReplaceInstUsesWith(SI, TrueVal);
9403 else
9404 return ReplaceInstUsesWith(SI, FalseVal);
9405 }
9406
Reid Spencer4fe16d62007-01-11 18:21:29 +00009407 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009408 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009409 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009410 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009411 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009412 } else {
9413 // Change: A = select B, false, C --> A = and !B, C
9414 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009415 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009416 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009418 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009419 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009420 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009421 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009422 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009423 } else {
9424 // Change: A = select B, C, true --> A = or !B, C
9425 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009426 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009427 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009428 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009429 }
9430 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009431
9432 // select a, b, a -> a&b
9433 // select a, a, b -> a|b
9434 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009435 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009436 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009438 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009439
Chris Lattner2eefe512004-04-09 19:05:30 +00009440 // Selecting between two integer constants?
9441 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9442 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009443 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009444 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009445 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009446 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009447 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009448 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009449 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009450 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009451 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009452 }
Chris Lattner457dd822004-06-09 07:59:58 +00009453
Reid Spencere4d87aa2006-12-23 06:05:41 +00009454 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009455
Reid Spencere4d87aa2006-12-23 06:05:41 +00009456 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009457 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009458 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009459 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009460 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009461 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009462 Value *X = IC->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009463 uint32_t Bits = X->getType()->getScalarSizeInBits();
Owen Andersond672ecb2009-07-03 00:17:18 +00009464 Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009466 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009467 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009468
9469 // Then cast to the appropriate width.
9470 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009471 }
9472 }
9473
9474
9475 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009476 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009477 // non-constant value, eliminate this whole mess. This corresponds to
9478 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009479 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009480 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009481 cast<Constant>(IC->getOperand(1))->isNullValue())
9482 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9483 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009484 isa<ConstantInt>(ICA->getOperand(1)) &&
9485 (ICA->getOperand(1) == TrueValC ||
9486 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009487 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9488 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009489 // know whether we have a icmp_ne or icmp_eq and whether the
9490 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009491 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009492 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009493 Value *V = ICA;
9494 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009495 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009496 Instruction::Xor, V, ICA->getOperand(1)), SI);
9497 return ReplaceInstUsesWith(SI, V);
9498 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009499 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009500 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009501
9502 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009503 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9504 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009505 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009506 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9507 // This is not safe in general for floating point:
9508 // consider X== -0, Y== +0.
9509 // It becomes safe if either operand is a nonzero constant.
9510 ConstantFP *CFPt, *CFPf;
9511 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9512 !CFPt->getValueAPF().isZero()) ||
9513 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9514 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009515 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009516 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009517 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009518 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009519 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009520 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009521
Reid Spencere4d87aa2006-12-23 06:05:41 +00009522 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009523 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009524 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9525 // This is not safe in general for floating point:
9526 // consider X== -0, Y== +0.
9527 // It becomes safe if either operand is a nonzero constant.
9528 ConstantFP *CFPt, *CFPf;
9529 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9530 !CFPt->getValueAPF().isZero()) ||
9531 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9532 !CFPf->getValueAPF().isZero()))
9533 return ReplaceInstUsesWith(SI, FalseVal);
9534 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009535 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009536 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9537 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009538 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009539 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009540 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009541 }
9542
9543 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009544 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9545 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9546 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009547
Chris Lattner87875da2005-01-13 22:52:24 +00009548 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9549 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9550 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009551 Instruction *AddOp = 0, *SubOp = 0;
9552
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009553 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9554 if (TI->getOpcode() == FI->getOpcode())
9555 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9556 return IV;
9557
9558 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9559 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009560 if ((TI->getOpcode() == Instruction::Sub &&
9561 FI->getOpcode() == Instruction::Add) ||
9562 (TI->getOpcode() == Instruction::FSub &&
9563 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009564 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009565 } else if ((FI->getOpcode() == Instruction::Sub &&
9566 TI->getOpcode() == Instruction::Add) ||
9567 (FI->getOpcode() == Instruction::FSub &&
9568 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009569 AddOp = TI; SubOp = FI;
9570 }
9571
9572 if (AddOp) {
9573 Value *OtherAddOp = 0;
9574 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9575 OtherAddOp = AddOp->getOperand(1);
9576 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9577 OtherAddOp = AddOp->getOperand(0);
9578 }
9579
9580 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009581 // So at this point we know we have (Y -> OtherAddOp):
9582 // select C, (add X, Y), (sub X, Z)
9583 Value *NegVal; // Compute -Z
9584 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009585 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009586 } else {
9587 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009588 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009589 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009590
9591 Value *NewTrueOp = OtherAddOp;
9592 Value *NewFalseOp = NegVal;
9593 if (AddOp != TI)
9594 std::swap(NewTrueOp, NewFalseOp);
9595 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009596 SelectInst::Create(CondVal, NewTrueOp,
9597 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009598
9599 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009600 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009601 }
9602 }
9603 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009604
Chris Lattnere576b912004-04-09 23:46:01 +00009605 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009606 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009607 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9608 if (FoldI)
9609 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009610 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009611
9612 if (BinaryOperator::isNot(CondVal)) {
9613 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9614 SI.setOperand(1, FalseVal);
9615 SI.setOperand(2, TrueVal);
9616 return &SI;
9617 }
9618
Chris Lattner3d69f462004-03-12 05:52:32 +00009619 return 0;
9620}
9621
Dan Gohmaneee962e2008-04-10 18:43:06 +00009622/// EnforceKnownAlignment - If the specified pointer points to an object that
9623/// we control, modify the object's alignment to PrefAlign. This isn't
9624/// often possible though. If alignment is important, a more reliable approach
9625/// is to simply align all global variables and allocation instructions to
9626/// their preferred alignment from the beginning.
9627///
9628static unsigned EnforceKnownAlignment(Value *V,
9629 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009630
Dan Gohmaneee962e2008-04-10 18:43:06 +00009631 User *U = dyn_cast<User>(V);
9632 if (!U) return Align;
9633
9634 switch (getOpcode(U)) {
9635 default: break;
9636 case Instruction::BitCast:
9637 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9638 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009639 // If all indexes are zero, it is just the alignment of the base pointer.
9640 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009641 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009642 if (!isa<Constant>(*i) ||
9643 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009644 AllZeroOperands = false;
9645 break;
9646 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009647
9648 if (AllZeroOperands) {
9649 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009651 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009652 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009653 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009654 }
9655
9656 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9657 // If there is a large requested alignment and we can, bump up the alignment
9658 // of the global.
9659 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009660 if (GV->getAlignment() >= PrefAlign)
9661 Align = GV->getAlignment();
9662 else {
9663 GV->setAlignment(PrefAlign);
9664 Align = PrefAlign;
9665 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009666 }
9667 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9668 // If there is a requested alignment and if this is an alloca, round up. We
9669 // don't do this for malloc, because some systems can't respect the request.
9670 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009671 if (AI->getAlignment() >= PrefAlign)
9672 Align = AI->getAlignment();
9673 else {
9674 AI->setAlignment(PrefAlign);
9675 Align = PrefAlign;
9676 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009677 }
9678 }
9679
9680 return Align;
9681}
9682
9683/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9684/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9685/// and it is more than the alignment of the ultimate object, see if we can
9686/// increase the alignment of the ultimate object, making this check succeed.
9687unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9688 unsigned PrefAlign) {
9689 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9690 sizeof(PrefAlign) * CHAR_BIT;
9691 APInt Mask = APInt::getAllOnesValue(BitWidth);
9692 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9693 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9694 unsigned TrailZ = KnownZero.countTrailingOnes();
9695 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9696
9697 if (PrefAlign > Align)
9698 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9699
9700 // We don't need to make any adjustment.
9701 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009702}
9703
Chris Lattnerf497b022008-01-13 23:50:23 +00009704Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009705 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009706 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009707 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009708 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009709
9710 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009711 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9712 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009713 return MI;
9714 }
9715
9716 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9717 // load/store.
9718 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9719 if (MemOpLength == 0) return 0;
9720
Chris Lattner37ac6082008-01-14 00:28:35 +00009721 // Source and destination pointer types are always "i8*" for intrinsic. See
9722 // if the size is something we can handle with a single primitive load/store.
9723 // A single load+store correctly handles overlapping memory in the memmove
9724 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009725 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009726 if (Size == 0) return MI; // Delete this mem transfer.
9727
9728 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009729 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009730
Chris Lattner37ac6082008-01-14 00:28:35 +00009731 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009732 Type *NewPtrTy =
9733 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009734
9735 // Memcpy forces the use of i8* for the source and destination. That means
9736 // that if you're using memcpy to move one double around, you'll get a cast
9737 // from double* to i8*. We'd much rather use a double load+store rather than
9738 // an i64 load+store, here because this improves the odds that the source or
9739 // dest address will be promotable. See if we can find a better type than the
9740 // integer datatype.
9741 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9742 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9743 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9744 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9745 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009746 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009747 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9748 if (STy->getNumElements() == 1)
9749 SrcETy = STy->getElementType(0);
9750 else
9751 break;
9752 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9753 if (ATy->getNumElements() == 1)
9754 SrcETy = ATy->getElementType();
9755 else
9756 break;
9757 } else
9758 break;
9759 }
9760
Dan Gohman8f8e2692008-05-23 01:52:21 +00009761 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009762 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009763 }
9764 }
9765
9766
Chris Lattnerf497b022008-01-13 23:50:23 +00009767 // If the memcpy/memmove provides better alignment info than we can
9768 // infer, use it.
9769 SrcAlign = std::max(SrcAlign, CopyAlign);
9770 DstAlign = std::max(DstAlign, CopyAlign);
9771
9772 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9773 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009774 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9775 InsertNewInstBefore(L, *MI);
9776 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9777
9778 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009779 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009780 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009781}
Chris Lattner3d69f462004-03-12 05:52:32 +00009782
Chris Lattner69ea9d22008-04-30 06:39:11 +00009783Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9784 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009785 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009786 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9787 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788 return MI;
9789 }
9790
9791 // Extract the length and alignment and fill if they are constant.
9792 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9793 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9794 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9795 return 0;
9796 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009797 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009798
9799 // If the length is zero, this is a no-op
9800 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9801
9802 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9803 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009804 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009805
9806 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009807 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009808
9809 // Alignment 0 is identity for alignment 1 for memset, but not store.
9810 if (Alignment == 0) Alignment = 1;
9811
9812 // Extract the fill value and store.
9813 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009814 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9815 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009816
9817 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009818 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009819 return MI;
9820 }
9821
9822 return 0;
9823}
9824
9825
Chris Lattner8b0ea312006-01-13 20:11:04 +00009826/// visitCallInst - CallInst simplification. This mostly only handles folding
9827/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9828/// the heavy lifting.
9829///
Chris Lattner9fe38862003-06-19 17:00:31 +00009830Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009831 // If the caller function is nounwind, mark the call as nounwind, even if the
9832 // callee isn't.
9833 if (CI.getParent()->getParent()->doesNotThrow() &&
9834 !CI.doesNotThrow()) {
9835 CI.setDoesNotThrow();
9836 return &CI;
9837 }
9838
9839
9840
Chris Lattner8b0ea312006-01-13 20:11:04 +00009841 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9842 if (!II) return visitCallSite(&CI);
9843
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009844 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9845 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009846 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009847 bool Changed = false;
9848
9849 // memmove/cpy/set of zero bytes is a noop.
9850 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9851 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9852
Chris Lattner35b9e482004-10-12 04:52:52 +00009853 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009854 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009855 // Replace the instruction with just byte operations. We would
9856 // transform other cases to loads/stores, but we don't know if
9857 // alignment is sufficient.
9858 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009859 }
9860
Chris Lattner35b9e482004-10-12 04:52:52 +00009861 // If we have a memmove and the source operation is a constant global,
9862 // then the source and dest pointers can't alias, so we can change this
9863 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009864 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009865 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9866 if (GVSrc->isConstant()) {
9867 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009868 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9869 const Type *Tys[1];
9870 Tys[0] = CI.getOperand(3)->getType();
9871 CI.setOperand(0,
9872 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009873 Changed = true;
9874 }
Chris Lattnera935db82008-05-28 05:30:41 +00009875
9876 // memmove(x,x,size) -> noop.
9877 if (MMI->getSource() == MMI->getDest())
9878 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009879 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009880
Chris Lattner95a959d2006-03-06 20:18:44 +00009881 // If we can determine a pointer alignment that is bigger than currently
9882 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009883 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009884 if (Instruction *I = SimplifyMemTransfer(MI))
9885 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009886 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9887 if (Instruction *I = SimplifyMemSet(MSI))
9888 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009889 }
9890
Chris Lattner8b0ea312006-01-13 20:11:04 +00009891 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 }
9893
9894 switch (II->getIntrinsicID()) {
9895 default: break;
9896 case Intrinsic::bswap:
9897 // bswap(bswap(x)) -> x
9898 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9899 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9900 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9901 break;
9902 case Intrinsic::ppc_altivec_lvx:
9903 case Intrinsic::ppc_altivec_lvxl:
9904 case Intrinsic::x86_sse_loadu_ps:
9905 case Intrinsic::x86_sse2_loadu_pd:
9906 case Intrinsic::x86_sse2_loadu_dq:
9907 // Turn PPC lvx -> load if the pointer is known aligned.
9908 // Turn X86 loadups -> load if the pointer is known aligned.
9909 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9910 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009911 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009912 CI);
9913 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009914 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 break;
9916 case Intrinsic::ppc_altivec_stvx:
9917 case Intrinsic::ppc_altivec_stvxl:
9918 // Turn stvx -> store if the pointer is known aligned.
9919 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9920 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009921 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009922 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9923 return new StoreInst(II->getOperand(1), Ptr);
9924 }
9925 break;
9926 case Intrinsic::x86_sse_storeu_ps:
9927 case Intrinsic::x86_sse2_storeu_pd:
9928 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009929 // Turn X86 storeu -> store if the pointer is known aligned.
9930 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9931 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009932 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009933 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9934 return new StoreInst(II->getOperand(2), Ptr);
9935 }
9936 break;
9937
9938 case Intrinsic::x86_sse_cvttss2si: {
9939 // These intrinsics only demands the 0th element of its input vector. If
9940 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009941 unsigned VWidth =
9942 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9943 APInt DemandedElts(VWidth, 1);
9944 APInt UndefElts(VWidth, 0);
9945 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009946 UndefElts)) {
9947 II->setOperand(1, V);
9948 return II;
9949 }
9950 break;
9951 }
9952
9953 case Intrinsic::ppc_altivec_vperm:
9954 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9955 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9956 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009957
Chris Lattner0521e3c2008-06-18 04:33:20 +00009958 // Check that all of the elements are integer constants or undefs.
9959 bool AllEltsOk = true;
9960 for (unsigned i = 0; i != 16; ++i) {
9961 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9962 !isa<UndefValue>(Mask->getOperand(i))) {
9963 AllEltsOk = false;
9964 break;
9965 }
9966 }
9967
9968 if (AllEltsOk) {
9969 // Cast the input vectors to byte vectors.
9970 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9971 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009972 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009973
Chris Lattner0521e3c2008-06-18 04:33:20 +00009974 // Only extract each element once.
9975 Value *ExtractedElts[32];
9976 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9977
Chris Lattnere2ed0572006-04-06 19:19:17 +00009978 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979 if (isa<UndefValue>(Mask->getOperand(i)))
9980 continue;
9981 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9982 Idx &= 31; // Match the hardware behavior.
9983
9984 if (ExtractedElts[Idx] == 0) {
9985 Instruction *Elt =
9986 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9987 InsertNewInstBefore(Elt, CI);
9988 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009989 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009990
Chris Lattner0521e3c2008-06-18 04:33:20 +00009991 // Insert this value into the result vector.
9992 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9993 i, "tmp");
9994 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009995 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009996 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009997 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009998 }
9999 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010000
Chris Lattner0521e3c2008-06-18 04:33:20 +000010001 case Intrinsic::stackrestore: {
10002 // If the save is right next to the restore, remove the restore. This can
10003 // happen when variable allocas are DCE'd.
10004 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10005 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10006 BasicBlock::iterator BI = SS;
10007 if (&*++BI == II)
10008 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010009 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010010 }
10011
10012 // Scan down this block to see if there is another stack restore in the
10013 // same block without an intervening call/alloca.
10014 BasicBlock::iterator BI = II;
10015 TerminatorInst *TI = II->getParent()->getTerminator();
10016 bool CannotRemove = false;
10017 for (++BI; &*BI != TI; ++BI) {
10018 if (isa<AllocaInst>(BI)) {
10019 CannotRemove = true;
10020 break;
10021 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010022 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10023 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10024 // If there is a stackrestore below this one, remove this one.
10025 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10026 return EraseInstFromFunction(CI);
10027 // Otherwise, ignore the intrinsic.
10028 } else {
10029 // If we found a non-intrinsic call, we can't remove the stack
10030 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010031 CannotRemove = true;
10032 break;
10033 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010034 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010035 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010036
10037 // If the stack restore is in a return/unwind block and if there are no
10038 // allocas or calls between the restore and the return, nuke the restore.
10039 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10040 return EraseInstFromFunction(CI);
10041 break;
10042 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010043 }
10044
Chris Lattner8b0ea312006-01-13 20:11:04 +000010045 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010046}
10047
10048// InvokeInst simplification
10049//
10050Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010051 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010052}
10053
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010054/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10055/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010056static bool isSafeToEliminateVarargsCast(const CallSite CS,
10057 const CastInst * const CI,
10058 const TargetData * const TD,
10059 const int ix) {
10060 if (!CI->isLosslessCast())
10061 return false;
10062
10063 // The size of ByVal arguments is derived from the type, so we
10064 // can't change to a type with a different size. If the size were
10065 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010066 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010067 return true;
10068
10069 const Type* SrcTy =
10070 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10071 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10072 if (!SrcTy->isSized() || !DstTy->isSized())
10073 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010074 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010075 return false;
10076 return true;
10077}
10078
Chris Lattnera44d8a22003-10-07 22:32:43 +000010079// visitCallSite - Improvements for call and invoke instructions.
10080//
10081Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010082 bool Changed = false;
10083
10084 // If the callee is a constexpr cast of a function, attempt to move the cast
10085 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010086 if (transformConstExprCastCall(CS)) return 0;
10087
Chris Lattner6c266db2003-10-07 22:54:13 +000010088 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010089
Chris Lattner08b22ec2005-05-13 07:09:09 +000010090 if (Function *CalleeF = dyn_cast<Function>(Callee))
10091 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10092 Instruction *OldCall = CS.getInstruction();
10093 // If the call and callee calling conventions don't match, this call must
10094 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010095 new StoreInst(Context->getConstantIntTrue(),
10096 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10097 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010098 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010099 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010100 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10101 return EraseInstFromFunction(*OldCall);
10102 return 0;
10103 }
10104
Chris Lattner17be6352004-10-18 02:59:09 +000010105 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10106 // This instruction is not reachable, just remove it. We insert a store to
10107 // undef so that we know that this code is not reachable, despite the fact
10108 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010109 new StoreInst(Context->getConstantIntTrue(),
10110 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010111 CS.getInstruction());
10112
10113 if (!CS.getInstruction()->use_empty())
10114 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010115 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010116
10117 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10118 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010119 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010120 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010121 }
Chris Lattner17be6352004-10-18 02:59:09 +000010122 return EraseInstFromFunction(*CS.getInstruction());
10123 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010124
Duncan Sandscdb6d922007-09-17 10:26:40 +000010125 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10126 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10127 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10128 return transformCallThroughTrampoline(CS);
10129
Chris Lattner6c266db2003-10-07 22:54:13 +000010130 const PointerType *PTy = cast<PointerType>(Callee->getType());
10131 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10132 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010133 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010134 // See if we can optimize any arguments passed through the varargs area of
10135 // the call.
10136 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010137 E = CS.arg_end(); I != E; ++I, ++ix) {
10138 CastInst *CI = dyn_cast<CastInst>(*I);
10139 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10140 *I = CI->getOperand(0);
10141 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010142 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010143 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010144 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010145
Duncan Sandsf0c33542007-12-19 21:13:37 +000010146 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010147 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010148 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010149 Changed = true;
10150 }
10151
Chris Lattner6c266db2003-10-07 22:54:13 +000010152 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010153}
10154
Chris Lattner9fe38862003-06-19 17:00:31 +000010155// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10156// attempt to move the cast to the arguments of the call/invoke.
10157//
10158bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10159 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10160 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010161 if (CE->getOpcode() != Instruction::BitCast ||
10162 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010164 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010165 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010166 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010167
10168 // Okay, this is a cast from a function to a different type. Unless doing so
10169 // would cause a type conversion of one of our arguments, change this call to
10170 // be a direct call with arguments casted to the appropriate types.
10171 //
10172 const FunctionType *FT = Callee->getFunctionType();
10173 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010174 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010175
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010176 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010177 return false; // TODO: Handle multiple return values.
10178
Chris Lattnerf78616b2004-01-14 06:06:08 +000010179 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010180 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010181 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010182 // Conversion is ok if changing from one pointer type to another or from
10183 // a pointer to an integer of the same size.
10184 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010185 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010186 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010187
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010188 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010189 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010190 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010191 return false; // Cannot transform this return value.
10192
Chris Lattner58d74912008-03-12 17:45:29 +000010193 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010194 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010195 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010196 return false; // Attribute not compatible with transformed value.
10197 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010198
Chris Lattnerf78616b2004-01-14 06:06:08 +000010199 // If the callsite is an invoke instruction, and the return value is used by
10200 // a PHI node in a successor, we cannot change the return type of the call
10201 // because there is no place to put the cast instruction (without breaking
10202 // the critical edge). Bail out in this case.
10203 if (!Caller->use_empty())
10204 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10205 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10206 UI != E; ++UI)
10207 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10208 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010209 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010210 return false;
10211 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010212
10213 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10214 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010215
Chris Lattner9fe38862003-06-19 17:00:31 +000010216 CallSite::arg_iterator AI = CS.arg_begin();
10217 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10218 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010219 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010220
10221 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010222 return false; // Cannot transform this parameter value.
10223
Devang Patel19c87462008-09-26 22:53:05 +000010224 if (CallerPAL.getParamAttributes(i + 1)
10225 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010226 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010227
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010228 // Converting from one pointer type to another or between a pointer and an
10229 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010230 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010231 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10232 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010233 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010234 }
10235
10236 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010237 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010238 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010239
Chris Lattner58d74912008-03-12 17:45:29 +000010240 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10241 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010242 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010243 // won't be dropping them. Check that these extra arguments have attributes
10244 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010245 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10246 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010247 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010248 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010249 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010250 return false;
10251 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010252
Chris Lattner9fe38862003-06-19 17:00:31 +000010253 // Okay, we decided that this is a safe thing to do: go ahead and start
10254 // inserting cast instructions as necessary...
10255 std::vector<Value*> Args;
10256 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010257 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010258 attrVec.reserve(NumCommonArgs);
10259
10260 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010261 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010262
10263 // If the return value is not being used, the type may not be compatible
10264 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010265 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010266
10267 // Add the new return attributes.
10268 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010269 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010270
10271 AI = CS.arg_begin();
10272 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10273 const Type *ParamTy = FT->getParamType(i);
10274 if ((*AI)->getType() == ParamTy) {
10275 Args.push_back(*AI);
10276 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010277 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010278 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010279 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010280 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010281 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010282
10283 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010284 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010285 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010286 }
10287
10288 // If the function takes more arguments than the call was taking, add them
10289 // now...
10290 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010291 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010292
10293 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010294 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010295 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010296 cerr << "WARNING: While resolving call to function '"
10297 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010298 } else {
10299 // Add all of the arguments in their promoted form to the arg list...
10300 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10301 const Type *PTy = getPromotedType((*AI)->getType());
10302 if (PTy != (*AI)->getType()) {
10303 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010304 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10305 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010306 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010307 InsertNewInstBefore(Cast, *Caller);
10308 Args.push_back(Cast);
10309 } else {
10310 Args.push_back(*AI);
10311 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010312
Duncan Sandse1e520f2008-01-13 08:02:44 +000010313 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010314 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010315 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010316 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010317 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010318 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010319
Devang Patel19c87462008-09-26 22:53:05 +000010320 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10321 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10322
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010323 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010324 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010325
Devang Patel05988662008-09-25 21:00:45 +000010326 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010327
Chris Lattner9fe38862003-06-19 17:00:31 +000010328 Instruction *NC;
10329 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010330 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010331 Args.begin(), Args.end(),
10332 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010333 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010334 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010335 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010336 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10337 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010338 CallInst *CI = cast<CallInst>(Caller);
10339 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010340 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010341 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010342 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 }
10344
Chris Lattner6934a042007-02-11 01:23:03 +000010345 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010346 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010347 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010348 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010349 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010350 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010351 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010352
10353 // If this is an invoke instruction, we should insert it after the first
10354 // non-phi, instruction in the normal successor block.
10355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010356 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010357 InsertNewInstBefore(NC, *I);
10358 } else {
10359 // Otherwise, it's a call, just insert cast right after the call instr
10360 InsertNewInstBefore(NC, *Caller);
10361 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010362 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010363 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010364 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010365 }
10366 }
10367
10368 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10369 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010370 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010371 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010372 return true;
10373}
10374
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375// transformCallThroughTrampoline - Turn a call to a function created by the
10376// init_trampoline intrinsic into a direct call to the underlying function.
10377//
10378Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10379 Value *Callee = CS.getCalledValue();
10380 const PointerType *PTy = cast<PointerType>(Callee->getType());
10381 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010382 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010383
10384 // If the call already has the 'nest' attribute somewhere then give up -
10385 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010386 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010387 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010388
10389 IntrinsicInst *Tramp =
10390 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10391
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010392 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010393 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10394 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10395
Devang Patel05988662008-09-25 21:00:45 +000010396 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010397 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010398 unsigned NestIdx = 1;
10399 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010400 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401
10402 // Look for a parameter marked with the 'nest' attribute.
10403 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10404 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010405 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 // Record the parameter type and any other attributes.
10407 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010408 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 break;
10410 }
10411
10412 if (NestTy) {
10413 Instruction *Caller = CS.getInstruction();
10414 std::vector<Value*> NewArgs;
10415 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10416
Devang Patel05988662008-09-25 21:00:45 +000010417 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010418 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010419
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010421 // mean appending it. Likewise for attributes.
10422
Devang Patel19c87462008-09-26 22:53:05 +000010423 // Add any result attributes.
10424 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010425 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010426
Duncan Sandscdb6d922007-09-17 10:26:40 +000010427 {
10428 unsigned Idx = 1;
10429 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10430 do {
10431 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010432 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 Value *NestVal = Tramp->getOperand(3);
10434 if (NestVal->getType() != NestTy)
10435 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10436 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010437 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 }
10439
10440 if (I == E)
10441 break;
10442
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010445 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010446 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010447 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448
10449 ++Idx, ++I;
10450 } while (1);
10451 }
10452
Devang Patel19c87462008-09-26 22:53:05 +000010453 // Add any function attributes.
10454 if (Attributes Attr = Attrs.getFnAttributes())
10455 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10456
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457 // The trampoline may have been bitcast to a bogus type (FTy).
10458 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010459 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460
Duncan Sandscdb6d922007-09-17 10:26:40 +000010461 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010462 NewTypes.reserve(FTy->getNumParams()+1);
10463
Duncan Sandscdb6d922007-09-17 10:26:40 +000010464 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010465 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010466 {
10467 unsigned Idx = 1;
10468 FunctionType::param_iterator I = FTy->param_begin(),
10469 E = FTy->param_end();
10470
10471 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010472 if (Idx == NestIdx)
10473 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010474 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010475
10476 if (I == E)
10477 break;
10478
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010479 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010480 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481
10482 ++Idx, ++I;
10483 } while (1);
10484 }
10485
10486 // Replace the trampoline call with a direct call. Let the generic
10487 // code sort out any function type mismatches.
10488 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010489 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10490 FTy->isVarArg());
10491 Constant *NewCallee =
10492 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10493 NestF : Context->getConstantExprBitCast(NestF,
10494 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010495 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010496
10497 Instruction *NewCaller;
10498 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010499 NewCaller = InvokeInst::Create(NewCallee,
10500 II->getNormalDest(), II->getUnwindDest(),
10501 NewArgs.begin(), NewArgs.end(),
10502 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010503 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010504 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010505 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010506 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10507 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010508 if (cast<CallInst>(Caller)->isTailCall())
10509 cast<CallInst>(NewCaller)->setTailCall();
10510 cast<CallInst>(NewCaller)->
10511 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010512 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010513 }
10514 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10515 Caller->replaceAllUsesWith(NewCaller);
10516 Caller->eraseFromParent();
10517 RemoveFromWorkList(Caller);
10518 return 0;
10519 }
10520 }
10521
10522 // Replace the trampoline call with a direct call. Since there is no 'nest'
10523 // parameter, there is no need to adjust the argument list. Let the generic
10524 // code sort out any function type mismatches.
10525 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010526 NestF->getType() == PTy ? NestF :
10527 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010528 CS.setCalledFunction(NewCallee);
10529 return CS.getInstruction();
10530}
10531
Chris Lattner7da52b22006-11-01 04:51:18 +000010532/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10533/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10534/// and a single binop.
10535Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10536 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010537 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010538 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010539 Value *LHSVal = FirstInst->getOperand(0);
10540 Value *RHSVal = FirstInst->getOperand(1);
10541
10542 const Type *LHSType = LHSVal->getType();
10543 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010544
10545 // Scan to see if all operands are the same opcode, all have one use, and all
10546 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010547 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010548 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010549 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010550 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010551 // types or GEP's with different index types.
10552 I->getOperand(0)->getType() != LHSType ||
10553 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010554 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010555
10556 // If they are CmpInst instructions, check their predicates
10557 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10558 if (cast<CmpInst>(I)->getPredicate() !=
10559 cast<CmpInst>(FirstInst)->getPredicate())
10560 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010561
10562 // Keep track of which operand needs a phi node.
10563 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10564 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010565 }
10566
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010567 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010568
Chris Lattner7da52b22006-11-01 04:51:18 +000010569 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010570 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010571 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010572 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010573 NewLHS = PHINode::Create(LHSType,
10574 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010575 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10576 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010577 InsertNewInstBefore(NewLHS, PN);
10578 LHSVal = NewLHS;
10579 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010580
10581 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010582 NewRHS = PHINode::Create(RHSType,
10583 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010584 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10585 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010586 InsertNewInstBefore(NewRHS, PN);
10587 RHSVal = NewRHS;
10588 }
10589
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010590 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010591 if (NewLHS || NewRHS) {
10592 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10593 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10594 if (NewLHS) {
10595 Value *NewInLHS = InInst->getOperand(0);
10596 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10597 }
10598 if (NewRHS) {
10599 Value *NewInRHS = InInst->getOperand(1);
10600 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10601 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010602 }
10603 }
10604
Chris Lattner7da52b22006-11-01 04:51:18 +000010605 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010606 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010607 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010608 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10609 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010610}
10611
Chris Lattner05f18922008-12-01 02:34:36 +000010612Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10613 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10614
10615 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10616 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010617 // This is true if all GEP bases are allocas and if all indices into them are
10618 // constants.
10619 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010620
10621 // Scan to see if all operands are the same opcode, all have one use, and all
10622 // kill their operands (i.e. the operands have one use).
10623 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10624 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10625 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10626 GEP->getNumOperands() != FirstInst->getNumOperands())
10627 return 0;
10628
Chris Lattner36d3e322009-02-21 00:46:50 +000010629 // Keep track of whether or not all GEPs are of alloca pointers.
10630 if (AllBasePointersAreAllocas &&
10631 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10632 !GEP->hasAllConstantIndices()))
10633 AllBasePointersAreAllocas = false;
10634
Chris Lattner05f18922008-12-01 02:34:36 +000010635 // Compare the operand lists.
10636 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10637 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10638 continue;
10639
10640 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10641 // if one of the PHIs has a constant for the index. The index may be
10642 // substantially cheaper to compute for the constants, so making it a
10643 // variable index could pessimize the path. This also handles the case
10644 // for struct indices, which must always be constant.
10645 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10646 isa<ConstantInt>(GEP->getOperand(op)))
10647 return 0;
10648
10649 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10650 return 0;
10651 FixedOperands[op] = 0; // Needs a PHI.
10652 }
10653 }
10654
Chris Lattner36d3e322009-02-21 00:46:50 +000010655 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010656 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010657 // offset calculation, but all the predecessors will have to materialize the
10658 // stack address into a register anyway. We'd actually rather *clone* the
10659 // load up into the predecessors so that we have a load of a gep of an alloca,
10660 // which can usually all be folded into the load.
10661 if (AllBasePointersAreAllocas)
10662 return 0;
10663
Chris Lattner05f18922008-12-01 02:34:36 +000010664 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10665 // that is variable.
10666 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10667
10668 bool HasAnyPHIs = false;
10669 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10670 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10671 Value *FirstOp = FirstInst->getOperand(i);
10672 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10673 FirstOp->getName()+".pn");
10674 InsertNewInstBefore(NewPN, PN);
10675
10676 NewPN->reserveOperandSpace(e);
10677 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10678 OperandPhis[i] = NewPN;
10679 FixedOperands[i] = NewPN;
10680 HasAnyPHIs = true;
10681 }
10682
10683
10684 // Add all operands to the new PHIs.
10685 if (HasAnyPHIs) {
10686 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10687 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10688 BasicBlock *InBB = PN.getIncomingBlock(i);
10689
10690 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10691 if (PHINode *OpPhi = OperandPhis[op])
10692 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10693 }
10694 }
10695
10696 Value *Base = FixedOperands[0];
10697 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10698 FixedOperands.end());
10699}
10700
10701
Chris Lattner21550882009-02-23 05:56:17 +000010702/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10703/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010704/// obvious the value of the load is not changed from the point of the load to
10705/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010706///
10707/// Finally, it is safe, but not profitable, to sink a load targetting a
10708/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10709/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010710static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010711 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10712
10713 for (++BBI; BBI != E; ++BBI)
10714 if (BBI->mayWriteToMemory())
10715 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010716
10717 // Check for non-address taken alloca. If not address-taken already, it isn't
10718 // profitable to do this xform.
10719 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10720 bool isAddressTaken = false;
10721 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10722 UI != E; ++UI) {
10723 if (isa<LoadInst>(UI)) continue;
10724 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10725 // If storing TO the alloca, then the address isn't taken.
10726 if (SI->getOperand(1) == AI) continue;
10727 }
10728 isAddressTaken = true;
10729 break;
10730 }
10731
Chris Lattner36d3e322009-02-21 00:46:50 +000010732 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010733 return false;
10734 }
10735
Chris Lattner36d3e322009-02-21 00:46:50 +000010736 // If this load is a load from a GEP with a constant offset from an alloca,
10737 // then we don't want to sink it. In its present form, it will be
10738 // load [constant stack offset]. Sinking it will cause us to have to
10739 // materialize the stack addresses in each predecessor in a register only to
10740 // do a shared load from register in the successor.
10741 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10742 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10743 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10744 return false;
10745
Chris Lattner76c73142006-11-01 07:13:54 +000010746 return true;
10747}
10748
Chris Lattner9fe38862003-06-19 17:00:31 +000010749
Chris Lattnerbac32862004-11-14 19:13:23 +000010750// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10751// operator and they all are only used by the PHI, PHI together their
10752// inputs, and do the operation once, to the result of the PHI.
10753Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10754 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10755
10756 // Scan the instruction, looking for input operations that can be folded away.
10757 // If all input operands to the phi are the same instruction (e.g. a cast from
10758 // the same type or "+42") we can pull the operation through the PHI, reducing
10759 // code size and simplifying code.
10760 Constant *ConstantOp = 0;
10761 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010762 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010763 if (isa<CastInst>(FirstInst)) {
10764 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010765 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010766 // Can fold binop, compare or shift here if the RHS is a constant,
10767 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010768 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010769 if (ConstantOp == 0)
10770 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010771 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10772 isVolatile = LI->isVolatile();
10773 // We can't sink the load if the loaded value could be modified between the
10774 // load and the PHI.
10775 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010776 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010777 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010778
10779 // If the PHI is of volatile loads and the load block has multiple
10780 // successors, sinking it would remove a load of the volatile value from
10781 // the path through the other successor.
10782 if (isVolatile &&
10783 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784 return 0;
10785
Chris Lattner9c080502006-11-01 07:43:41 +000010786 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010787 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010788 } else {
10789 return 0; // Cannot fold this operation.
10790 }
10791
10792 // Check to see if all arguments are the same operation.
10793 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10794 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10795 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010796 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010797 return 0;
10798 if (CastSrcTy) {
10799 if (I->getOperand(0)->getType() != CastSrcTy)
10800 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010801 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010802 // We can't sink the load if the loaded value could be modified between
10803 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010804 if (LI->isVolatile() != isVolatile ||
10805 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010806 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010807 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010808
Chris Lattner71042962008-07-08 17:18:32 +000010809 // If the PHI is of volatile loads and the load block has multiple
10810 // successors, sinking it would remove a load of the volatile value from
10811 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010812 if (isVolatile &&
10813 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10814 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010815
Chris Lattnerbac32862004-11-14 19:13:23 +000010816 } else if (I->getOperand(1) != ConstantOp) {
10817 return 0;
10818 }
10819 }
10820
10821 // Okay, they are all the same operation. Create a new PHI node of the
10822 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010823 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10824 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010825 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010826
10827 Value *InVal = FirstInst->getOperand(0);
10828 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010829
10830 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010831 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10832 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10833 if (NewInVal != InVal)
10834 InVal = 0;
10835 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10836 }
10837
10838 Value *PhiVal;
10839 if (InVal) {
10840 // The new PHI unions all of the same values together. This is really
10841 // common, so we handle it intelligently here for compile-time speed.
10842 PhiVal = InVal;
10843 delete NewPN;
10844 } else {
10845 InsertNewInstBefore(NewPN, PN);
10846 PhiVal = NewPN;
10847 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010848
Chris Lattnerbac32862004-11-14 19:13:23 +000010849 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010850 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010851 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010852 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010853 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010854 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010855 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010856 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010857 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10858
10859 // If this was a volatile load that we are merging, make sure to loop through
10860 // and mark all the input loads as non-volatile. If we don't do this, we will
10861 // insert a new volatile load and the old ones will not be deletable.
10862 if (isVolatile)
10863 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10864 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10865
10866 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010867}
Chris Lattnera1be5662002-05-02 17:06:02 +000010868
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010869/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10870/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010871static bool DeadPHICycle(PHINode *PN,
10872 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010873 if (PN->use_empty()) return true;
10874 if (!PN->hasOneUse()) return false;
10875
10876 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010877 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010878 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010879
10880 // Don't scan crazily complex things.
10881 if (PotentiallyDeadPHIs.size() == 16)
10882 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010883
10884 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10885 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010886
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010887 return false;
10888}
10889
Chris Lattnercf5008a2007-11-06 21:52:06 +000010890/// PHIsEqualValue - Return true if this phi node is always equal to
10891/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10892/// z = some value; x = phi (y, z); y = phi (x, z)
10893static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10894 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10895 // See if we already saw this PHI node.
10896 if (!ValueEqualPHIs.insert(PN))
10897 return true;
10898
10899 // Don't scan crazily complex things.
10900 if (ValueEqualPHIs.size() == 16)
10901 return false;
10902
10903 // Scan the operands to see if they are either phi nodes or are equal to
10904 // the value.
10905 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10906 Value *Op = PN->getIncomingValue(i);
10907 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10908 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10909 return false;
10910 } else if (Op != NonPhiInVal)
10911 return false;
10912 }
10913
10914 return true;
10915}
10916
10917
Chris Lattner473945d2002-05-06 18:06:38 +000010918// PHINode simplification
10919//
Chris Lattner7e708292002-06-25 16:13:24 +000010920Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010921 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010922 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010923
Owen Anderson7e057142006-07-10 22:03:18 +000010924 if (Value *V = PN.hasConstantValue())
10925 return ReplaceInstUsesWith(PN, V);
10926
Owen Anderson7e057142006-07-10 22:03:18 +000010927 // If all PHI operands are the same operation, pull them through the PHI,
10928 // reducing code size.
10929 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010930 isa<Instruction>(PN.getIncomingValue(1)) &&
10931 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10932 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10933 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10934 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010935 PN.getIncomingValue(0)->hasOneUse())
10936 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10937 return Result;
10938
10939 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10940 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10941 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010942 if (PN.hasOneUse()) {
10943 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10944 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010945 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010946 PotentiallyDeadPHIs.insert(&PN);
10947 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010948 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010949 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010950
10951 // If this phi has a single use, and if that use just computes a value for
10952 // the next iteration of a loop, delete the phi. This occurs with unused
10953 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10954 // common case here is good because the only other things that catch this
10955 // are induction variable analysis (sometimes) and ADCE, which is only run
10956 // late.
10957 if (PHIUser->hasOneUse() &&
10958 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10959 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010960 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010961 }
10962 }
Owen Anderson7e057142006-07-10 22:03:18 +000010963
Chris Lattnercf5008a2007-11-06 21:52:06 +000010964 // We sometimes end up with phi cycles that non-obviously end up being the
10965 // same value, for example:
10966 // z = some value; x = phi (y, z); y = phi (x, z)
10967 // where the phi nodes don't necessarily need to be in the same block. Do a
10968 // quick check to see if the PHI node only contains a single non-phi value, if
10969 // so, scan to see if the phi cycle is actually equal to that value.
10970 {
10971 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10972 // Scan for the first non-phi operand.
10973 while (InValNo != NumOperandVals &&
10974 isa<PHINode>(PN.getIncomingValue(InValNo)))
10975 ++InValNo;
10976
10977 if (InValNo != NumOperandVals) {
10978 Value *NonPhiInVal = PN.getOperand(InValNo);
10979
10980 // Scan the rest of the operands to see if there are any conflicts, if so
10981 // there is no need to recursively scan other phis.
10982 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10983 Value *OpVal = PN.getIncomingValue(InValNo);
10984 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10985 break;
10986 }
10987
10988 // If we scanned over all operands, then we have one unique value plus
10989 // phi values. Scan PHI nodes to see if they all merge in each other or
10990 // the value.
10991 if (InValNo == NumOperandVals) {
10992 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10993 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10994 return ReplaceInstUsesWith(PN, NonPhiInVal);
10995 }
10996 }
10997 }
Chris Lattner60921c92003-12-19 05:58:40 +000010998 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010999}
11000
Reid Spencer17212df2006-12-12 09:18:51 +000011001static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11002 Instruction *InsertPoint,
11003 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000011004 unsigned PtrSize = DTy->getScalarSizeInBits();
11005 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000011006 // We must cast correctly to the pointer type. Ensure that we
11007 // sign extend the integer value if it is smaller as this is
11008 // used for address computation.
11009 Instruction::CastOps opcode =
11010 (VTySize < PtrSize ? Instruction::SExt :
11011 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11012 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000011013}
11014
Chris Lattnera1be5662002-05-02 17:06:02 +000011015
Chris Lattner7e708292002-06-25 16:13:24 +000011016Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011017 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011018 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011019 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011020 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011021 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011022
Chris Lattnere87597f2004-10-16 18:11:37 +000011023 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011024 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011025
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011026 bool HasZeroPointerIndex = false;
11027 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11028 HasZeroPointerIndex = C->isNullValue();
11029
11030 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011031 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011032
Chris Lattner28977af2004-04-05 01:30:19 +000011033 // Eliminate unneeded casts for indices.
11034 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011035
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011036 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011037 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11038 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011039 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011040 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011041 if (CI->getOpcode() == Instruction::ZExt ||
11042 CI->getOpcode() == Instruction::SExt) {
11043 const Type *SrcTy = CI->getOperand(0)->getType();
11044 // We can eliminate a cast from i32 to i64 iff the target
11045 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011046 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011047 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011048 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011049 }
11050 }
11051 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011052 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011053 // to what we need. If narrower, sign-extend it to what we need.
11054 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011055 // insert it. This explicit cast can make subsequent optimizations more
11056 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011057 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011058 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011059 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011060 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011061 MadeChange = true;
11062 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011063 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11064 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011065 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011066 MadeChange = true;
11067 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011068 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11069 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011070 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011071 MadeChange = true;
11072 } else {
11073 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11074 GEP);
11075 *i = Op;
11076 MadeChange = true;
11077 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011078 }
Chris Lattner28977af2004-04-05 01:30:19 +000011079 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011080 }
Chris Lattner28977af2004-04-05 01:30:19 +000011081 if (MadeChange) return &GEP;
11082
Chris Lattner90ac28c2002-08-02 19:29:35 +000011083 // Combine Indices - If the source pointer to this getelementptr instruction
11084 // is a getelementptr instruction, combine the indices of the two
11085 // getelementptr instructions into a single instruction.
11086 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011087 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011088 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011089 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011090
11091 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011092 // Note that if our source is a gep chain itself that we wait for that
11093 // chain to be resolved before we perform this transformation. This
11094 // avoids us creating a TON of code in some cases.
11095 //
11096 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11097 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11098 return 0; // Wait until our source is folded to completion.
11099
Chris Lattner72588fc2007-02-15 22:48:32 +000011100 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011101
11102 // Find out whether the last index in the source GEP is a sequential idx.
11103 bool EndsWithSequential = false;
11104 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11105 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011106 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011107
Chris Lattner90ac28c2002-08-02 19:29:35 +000011108 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011109 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011110 // Replace: gep (gep %P, long B), long A, ...
11111 // With: T = long A+B; gep %P, T, ...
11112 //
Chris Lattner620ce142004-05-07 22:09:22 +000011113 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011114 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011115 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011116 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011117 Sum = SO1;
11118 } else {
11119 // If they aren't the same type, convert both to an integer of the
11120 // target's pointer size.
11121 if (SO1->getType() != GO1->getType()) {
11122 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011123 SO1 =
11124 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011125 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011126 GO1 =
11127 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011128 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011129 unsigned PS = TD->getPointerSizeInBits();
11130 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011131 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011132 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011133
Duncan Sands514ab342007-11-01 20:53:16 +000011134 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011135 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011136 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011137 } else {
11138 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011139 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11140 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011141 }
11142 }
11143 }
Chris Lattner620ce142004-05-07 22:09:22 +000011144 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011145 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11146 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011147 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011148 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011149 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011150 }
Chris Lattner28977af2004-04-05 01:30:19 +000011151 }
Chris Lattner620ce142004-05-07 22:09:22 +000011152
11153 // Recycle the GEP we already have if possible.
11154 if (SrcGEPOperands.size() == 2) {
11155 GEP.setOperand(0, SrcGEPOperands[0]);
11156 GEP.setOperand(1, Sum);
11157 return &GEP;
11158 } else {
11159 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11160 SrcGEPOperands.end()-1);
11161 Indices.push_back(Sum);
11162 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11163 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011164 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011165 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011166 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011167 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011168 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11169 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011170 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11171 }
11172
11173 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011174 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11175 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011176
Chris Lattner620ce142004-05-07 22:09:22 +000011177 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011178 // GEP of global variable. If all of the indices for this GEP are
11179 // constants, we can promote this to a constexpr instead of an instruction.
11180
11181 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011182 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011183 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11184 for (; I != E && isa<Constant>(*I); ++I)
11185 Indices.push_back(cast<Constant>(*I));
11186
11187 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011188 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011189 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011190
11191 // Replace all uses of the GEP with the new constexpr...
11192 return ReplaceInstUsesWith(GEP, CE);
11193 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011194 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011195 if (!isa<PointerType>(X->getType())) {
11196 // Not interesting. Source pointer must be a cast from pointer.
11197 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011198 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11199 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011200 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011201 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11202 // into : GEP i8* X, ...
11203 //
Chris Lattnereed48272005-09-13 00:40:14 +000011204 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011205 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11206 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011207 if (const ArrayType *CATy =
11208 dyn_cast<ArrayType>(CPTy->getElementType())) {
11209 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11210 if (CATy->getElementType() == XTy->getElementType()) {
11211 // -> GEP i8* X, ...
11212 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11213 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11214 GEP.getName());
11215 } else if (const ArrayType *XATy =
11216 dyn_cast<ArrayType>(XTy->getElementType())) {
11217 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011218 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011219 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011220 // At this point, we know that the cast source type is a pointer
11221 // to an array of the same type as the destination pointer
11222 // array. Because the array type is never stepped over (there
11223 // is a leading zero) we can fold the cast into this GEP.
11224 GEP.setOperand(0, X);
11225 return &GEP;
11226 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011227 }
11228 }
Chris Lattnereed48272005-09-13 00:40:14 +000011229 } else if (GEP.getNumOperands() == 2) {
11230 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011231 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11232 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011233 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11234 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11235 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011236 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11237 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011238 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011239 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011240 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011241 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011242 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011243 // V and GEP are both pointer types --> BitCast
11244 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011245 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011246
11247 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011248 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011249 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011250 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011251
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011252 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011253 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011254 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011255
11256 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11257 // allow either a mul, shift, or constant here.
11258 Value *NewIdx = 0;
11259 ConstantInt *Scale = 0;
11260 if (ArrayEltSize == 1) {
11261 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011262 Scale =
11263 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011264 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011265 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011266 Scale = CI;
11267 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11268 if (Inst->getOpcode() == Instruction::Shl &&
11269 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011270 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11271 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011272 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011273 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011274 NewIdx = Inst->getOperand(0);
11275 } else if (Inst->getOpcode() == Instruction::Mul &&
11276 isa<ConstantInt>(Inst->getOperand(1))) {
11277 Scale = cast<ConstantInt>(Inst->getOperand(1));
11278 NewIdx = Inst->getOperand(0);
11279 }
11280 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011281
Chris Lattner7835cdd2005-09-13 18:36:04 +000011282 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011283 // out, perform the transformation. Note, we don't know whether Scale is
11284 // signed or not. We'll use unsigned version of division/modulo
11285 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011286 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011287 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011288 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011289 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011290 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011291 Constant *C =
11292 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011293 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011294 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011295 NewIdx = InsertNewInstBefore(Sc, GEP);
11296 }
11297
11298 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011299 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011300 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011301 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011302 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011303 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011304 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11305 // The NewGEP must be pointer typed, so must the old one -> BitCast
11306 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011307 }
11308 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011309 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011310 }
Chris Lattner58407792009-01-09 04:53:57 +000011311
Chris Lattner46cd5a12009-01-09 05:44:56 +000011312 /// See if we can simplify:
11313 /// X = bitcast A to B*
11314 /// Y = gep X, <...constant indices...>
11315 /// into a gep of the original struct. This is important for SROA and alias
11316 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011317 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011318 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11319 // Determine how much the GEP moves the pointer. We are guaranteed to get
11320 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011321 ConstantInt *OffsetV =
11322 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011323 int64_t Offset = OffsetV->getSExtValue();
11324
11325 // If this GEP instruction doesn't move the pointer, just replace the GEP
11326 // with a bitcast of the real input to the dest type.
11327 if (Offset == 0) {
11328 // If the bitcast is of an allocation, and the allocation will be
11329 // converted to match the type of the cast, don't touch this.
11330 if (isa<AllocationInst>(BCI->getOperand(0))) {
11331 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11332 if (Instruction *I = visitBitCast(*BCI)) {
11333 if (I != BCI) {
11334 I->takeName(BCI);
11335 BCI->getParent()->getInstList().insert(BCI, I);
11336 ReplaceInstUsesWith(*BCI, I);
11337 }
11338 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011339 }
Chris Lattner58407792009-01-09 04:53:57 +000011340 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011341 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011342 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011343
11344 // Otherwise, if the offset is non-zero, we need to find out if there is a
11345 // field at Offset in 'A's type. If so, we can pull the cast through the
11346 // GEP.
11347 SmallVector<Value*, 8> NewIndices;
11348 const Type *InTy =
11349 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011350 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011351 Instruction *NGEP =
11352 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11353 NewIndices.end());
11354 if (NGEP->getType() == GEP.getType()) return NGEP;
11355 InsertNewInstBefore(NGEP, GEP);
11356 NGEP->takeName(&GEP);
11357 return new BitCastInst(NGEP, GEP.getType());
11358 }
Chris Lattner58407792009-01-09 04:53:57 +000011359 }
11360 }
11361
Chris Lattner8a2a3112001-12-14 16:52:21 +000011362 return 0;
11363}
11364
Chris Lattner0864acf2002-11-04 16:18:53 +000011365Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11366 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011367 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011368 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11369 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011370 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011371 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011372
11373 // Create and insert the replacement instruction...
11374 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011375 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011376 else {
11377 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011378 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011379 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011380
11381 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011382
Chris Lattner0864acf2002-11-04 16:18:53 +000011383 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011384 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011385 //
11386 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011387 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011388
11389 // Now that I is pointing to the first non-allocation-inst in the block,
11390 // insert our getelementptr instruction...
11391 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011392 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011393 Value *Idx[2];
11394 Idx[0] = NullIdx;
11395 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011396 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11397 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011398
11399 // Now make everything use the getelementptr instead of the original
11400 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011401 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011402 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011403 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011404 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011405 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011406
Dan Gohman6893cd72009-01-13 20:18:38 +000011407 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11408 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011409 // Note that we only do this for alloca's, because malloc should allocate
11410 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011411 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011412 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011413
11414 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11415 if (AI.getAlignment() == 0)
11416 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11417 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011418
Chris Lattner0864acf2002-11-04 16:18:53 +000011419 return 0;
11420}
11421
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011422Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11423 Value *Op = FI.getOperand(0);
11424
Chris Lattner17be6352004-10-18 02:59:09 +000011425 // free undef -> unreachable.
11426 if (isa<UndefValue>(Op)) {
11427 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011428 new StoreInst(Context->getConstantIntTrue(),
11429 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011430 return EraseInstFromFunction(FI);
11431 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011432
Chris Lattner6160e852004-02-28 04:57:37 +000011433 // If we have 'free null' delete the instruction. This can happen in stl code
11434 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011435 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011436 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011437
11438 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11439 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11440 FI.setOperand(0, CI->getOperand(0));
11441 return &FI;
11442 }
11443
11444 // Change free (gep X, 0,0,0,0) into free(X)
11445 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11446 if (GEPI->hasAllZeroIndices()) {
11447 AddToWorkList(GEPI);
11448 FI.setOperand(0, GEPI->getOperand(0));
11449 return &FI;
11450 }
11451 }
11452
11453 // Change free(malloc) into nothing, if the malloc has a single use.
11454 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11455 if (MI->hasOneUse()) {
11456 EraseInstFromFunction(FI);
11457 return EraseInstFromFunction(*MI);
11458 }
Chris Lattner6160e852004-02-28 04:57:37 +000011459
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011460 return 0;
11461}
11462
11463
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011464/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011465static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011466 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011467 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011468 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011469 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011470
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011471 if (TD) {
11472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11473 // Instead of loading constant c string, use corresponding integer value
11474 // directly if string length is small enough.
11475 std::string Str;
11476 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11477 unsigned len = Str.length();
11478 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11479 unsigned numBits = Ty->getPrimitiveSizeInBits();
11480 // Replace LI with immediate integer store.
11481 if ((numBits >> 3) == len + 1) {
11482 APInt StrVal(numBits, 0);
11483 APInt SingleChar(numBits, 0);
11484 if (TD->isLittleEndian()) {
11485 for (signed i = len-1; i >= 0; i--) {
11486 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11487 StrVal = (StrVal << 8) | SingleChar;
11488 }
11489 } else {
11490 for (unsigned i = 0; i < len; i++) {
11491 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11492 StrVal = (StrVal << 8) | SingleChar;
11493 }
11494 // Append NULL at the end.
11495 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011496 StrVal = (StrVal << 8) | SingleChar;
11497 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011498 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011499 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011500 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011501 }
11502 }
11503 }
11504
Mon P Wang6753f952009-02-07 22:19:29 +000011505 const PointerType *DestTy = cast<PointerType>(CI->getType());
11506 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011507 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011508
11509 // If the address spaces don't match, don't eliminate the cast.
11510 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11511 return 0;
11512
Chris Lattnerb89e0712004-07-13 01:49:43 +000011513 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011514
Reid Spencer42230162007-01-22 05:51:25 +000011515 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011516 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011517 // If the source is an array, the code below will not succeed. Check to
11518 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11519 // constants.
11520 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11521 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11522 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011523 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011524 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11525 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011526 SrcTy = cast<PointerType>(CastOp->getType());
11527 SrcPTy = SrcTy->getElementType();
11528 }
11529
Reid Spencer42230162007-01-22 05:51:25 +000011530 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011531 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011532 // Do not allow turning this into a load of an integer, which is then
11533 // casted to a pointer, this pessimizes pointer analysis a lot.
11534 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011535 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11536 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011537
Chris Lattnerf9527852005-01-31 04:50:46 +000011538 // Okay, we are casting from one integer or pointer type to another of
11539 // the same size. Instead of casting the pointer before the load, cast
11540 // the result of the loaded value.
11541 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11542 CI->getName(),
11543 LI.isVolatile()),LI);
11544 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011545 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011546 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011547 }
11548 }
11549 return 0;
11550}
11551
Chris Lattner833b8a42003-06-26 05:06:25 +000011552Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11553 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011554
Dan Gohman9941f742007-07-20 16:34:21 +000011555 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011556 unsigned KnownAlign =
11557 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011558 if (KnownAlign >
11559 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11560 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011561 LI.setAlignment(KnownAlign);
11562
Chris Lattner37366c12005-05-01 04:24:53 +000011563 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011564 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011565 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011566 return Res;
11567
11568 // None of the following transforms are legal for volatile loads.
11569 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011570
Dan Gohman2276a7b2008-10-15 23:19:35 +000011571 // Do really simple store-to-load forwarding and load CSE, to catch cases
11572 // where there are several consequtive memory accesses to the same location,
11573 // separated by a few arithmetic operations.
11574 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011575 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11576 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011577
Christopher Lambb15147e2007-12-29 07:56:53 +000011578 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11579 const Value *GEPI0 = GEPI->getOperand(0);
11580 // TODO: Consider a target hook for valid address spaces for this xform.
11581 if (isa<ConstantPointerNull>(GEPI0) &&
11582 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011583 // Insert a new store to null instruction before the load to indicate
11584 // that this code is not reachable. We do this instead of inserting
11585 // an unreachable instruction directly because we cannot modify the
11586 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011587 new StoreInst(Context->getUndef(LI.getType()),
11588 Context->getNullValue(Op->getType()), &LI);
11589 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011590 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011591 }
Chris Lattner37366c12005-05-01 04:24:53 +000011592
Chris Lattnere87597f2004-10-16 18:11:37 +000011593 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011594 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011595 // TODO: Consider a target hook for valid address spaces for this xform.
11596 if (isa<UndefValue>(C) || (C->isNullValue() &&
11597 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011598 // Insert a new store to null instruction before the load to indicate that
11599 // this code is not reachable. We do this instead of inserting an
11600 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011601 new StoreInst(Context->getUndef(LI.getType()),
11602 Context->getNullValue(Op->getType()), &LI);
11603 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011604 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011605
Chris Lattnere87597f2004-10-16 18:11:37 +000011606 // Instcombine load (constant global) into the value loaded.
11607 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011608 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011609 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011610
Chris Lattnere87597f2004-10-16 18:11:37 +000011611 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011612 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011613 if (CE->getOpcode() == Instruction::GetElementPtr) {
11614 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011615 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011616 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011617 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11618 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011619 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011620 if (CE->getOperand(0)->isNullValue()) {
11621 // Insert a new store to null instruction before the load to indicate
11622 // that this code is not reachable. We do this instead of inserting
11623 // an unreachable instruction directly because we cannot modify the
11624 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011625 new StoreInst(Context->getUndef(LI.getType()),
11626 Context->getNullValue(Op->getType()), &LI);
11627 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011628 }
11629
Reid Spencer3da59db2006-11-27 01:05:10 +000011630 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011631 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011632 return Res;
11633 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011634 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011635 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011636
11637 // If this load comes from anywhere in a constant global, and if the global
11638 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011639 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011640 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011641 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011642 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011643 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011644 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011645 }
11646 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011647
Chris Lattner37366c12005-05-01 04:24:53 +000011648 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011649 // Change select and PHI nodes to select values instead of addresses: this
11650 // helps alias analysis out a lot, allows many others simplifications, and
11651 // exposes redundancy in the code.
11652 //
11653 // Note that we cannot do the transformation unless we know that the
11654 // introduced loads cannot trap! Something like this is valid as long as
11655 // the condition is always false: load (select bool %C, int* null, int* %G),
11656 // but it would not be valid if we transformed it to load from null
11657 // unconditionally.
11658 //
11659 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11660 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011661 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11662 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011663 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011664 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011665 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011666 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011667 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011668 }
11669
Chris Lattner684fe212004-09-23 15:46:00 +000011670 // load (select (cond, null, P)) -> load P
11671 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11672 if (C->isNullValue()) {
11673 LI.setOperand(0, SI->getOperand(2));
11674 return &LI;
11675 }
11676
11677 // load (select (cond, P, null)) -> load P
11678 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11679 if (C->isNullValue()) {
11680 LI.setOperand(0, SI->getOperand(1));
11681 return &LI;
11682 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011683 }
11684 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011685 return 0;
11686}
11687
Reid Spencer55af2b52007-01-19 21:20:31 +000011688/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011689/// when possible. This makes it generally easy to do alias analysis and/or
11690/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011691static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11692 User *CI = cast<User>(SI.getOperand(1));
11693 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011694 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011695
11696 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011697 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11698 if (SrcTy == 0) return 0;
11699
11700 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011701
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011702 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11703 return 0;
11704
Chris Lattner3914f722009-01-24 01:00:13 +000011705 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11706 /// to its first element. This allows us to handle things like:
11707 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11708 /// on 32-bit hosts.
11709 SmallVector<Value*, 4> NewGEPIndices;
11710
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011711 // If the source is an array, the code below will not succeed. Check to
11712 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11713 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011714 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11715 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011716 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011717 NewGEPIndices.push_back(Zero);
11718
11719 while (1) {
11720 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011721 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011722 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011723 NewGEPIndices.push_back(Zero);
11724 SrcPTy = STy->getElementType(0);
11725 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11726 NewGEPIndices.push_back(Zero);
11727 SrcPTy = ATy->getElementType();
11728 } else {
11729 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011730 }
Chris Lattner3914f722009-01-24 01:00:13 +000011731 }
11732
Owen Andersond672ecb2009-07-03 00:17:18 +000011733 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011734 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011735
11736 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11737 return 0;
11738
Chris Lattner71759c42009-01-16 20:12:52 +000011739 // If the pointers point into different address spaces or if they point to
11740 // values with different sizes, we can't do the transformation.
11741 if (SrcTy->getAddressSpace() !=
11742 cast<PointerType>(CI->getType())->getAddressSpace() ||
11743 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011744 IC.getTargetData().getTypeSizeInBits(DestPTy))
11745 return 0;
11746
11747 // Okay, we are casting from one integer or pointer type to another of
11748 // the same size. Instead of casting the pointer before
11749 // the store, cast the value to be stored.
11750 Value *NewCast;
11751 Value *SIOp0 = SI.getOperand(0);
11752 Instruction::CastOps opcode = Instruction::BitCast;
11753 const Type* CastSrcTy = SIOp0->getType();
11754 const Type* CastDstTy = SrcPTy;
11755 if (isa<PointerType>(CastDstTy)) {
11756 if (CastSrcTy->isInteger())
11757 opcode = Instruction::IntToPtr;
11758 } else if (isa<IntegerType>(CastDstTy)) {
11759 if (isa<PointerType>(SIOp0->getType()))
11760 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011761 }
Chris Lattner3914f722009-01-24 01:00:13 +000011762
11763 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11764 // emit a GEP to index into its first field.
11765 if (!NewGEPIndices.empty()) {
11766 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011767 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011768 NewGEPIndices.size());
11769 else
11770 CastOp = IC.InsertNewInstBefore(
11771 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11772 NewGEPIndices.end()), SI);
11773 }
11774
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011775 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011776 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011777 else
11778 NewCast = IC.InsertNewInstBefore(
11779 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11780 SI);
11781 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011782}
11783
Chris Lattner4aebaee2008-11-27 08:56:30 +000011784/// equivalentAddressValues - Test if A and B will obviously have the same
11785/// value. This includes recognizing that %t0 and %t1 will have the same
11786/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011787/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011788/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011789/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011790/// %t2 = load i32* %t1
11791///
11792static bool equivalentAddressValues(Value *A, Value *B) {
11793 // Test if the values are trivially equivalent.
11794 if (A == B) return true;
11795
11796 // Test if the values come form identical arithmetic instructions.
11797 if (isa<BinaryOperator>(A) ||
11798 isa<CastInst>(A) ||
11799 isa<PHINode>(A) ||
11800 isa<GetElementPtrInst>(A))
11801 if (Instruction *BI = dyn_cast<Instruction>(B))
11802 if (cast<Instruction>(A)->isIdenticalTo(BI))
11803 return true;
11804
11805 // Otherwise they may not be equivalent.
11806 return false;
11807}
11808
Dale Johannesen4945c652009-03-03 21:26:39 +000011809// If this instruction has two uses, one of which is a llvm.dbg.declare,
11810// return the llvm.dbg.declare.
11811DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11812 if (!V->hasNUses(2))
11813 return 0;
11814 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11815 UI != E; ++UI) {
11816 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11817 return DI;
11818 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11819 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11820 return DI;
11821 }
11822 }
11823 return 0;
11824}
11825
Chris Lattner2f503e62005-01-31 05:36:43 +000011826Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11827 Value *Val = SI.getOperand(0);
11828 Value *Ptr = SI.getOperand(1);
11829
11830 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011831 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011832 ++NumCombined;
11833 return 0;
11834 }
Chris Lattner836692d2007-01-15 06:51:56 +000011835
11836 // If the RHS is an alloca with a single use, zapify the store, making the
11837 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011838 // If the RHS is an alloca with a two uses, the other one being a
11839 // llvm.dbg.declare, zapify the store and the declare, making the
11840 // alloca dead. We must do this to prevent declare's from affecting
11841 // codegen.
11842 if (!SI.isVolatile()) {
11843 if (Ptr->hasOneUse()) {
11844 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011845 EraseInstFromFunction(SI);
11846 ++NumCombined;
11847 return 0;
11848 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011849 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11850 if (isa<AllocaInst>(GEP->getOperand(0))) {
11851 if (GEP->getOperand(0)->hasOneUse()) {
11852 EraseInstFromFunction(SI);
11853 ++NumCombined;
11854 return 0;
11855 }
11856 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11857 EraseInstFromFunction(*DI);
11858 EraseInstFromFunction(SI);
11859 ++NumCombined;
11860 return 0;
11861 }
11862 }
11863 }
11864 }
11865 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11866 EraseInstFromFunction(*DI);
11867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
Chris Lattner836692d2007-01-15 06:51:56 +000011871 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011872
Dan Gohman9941f742007-07-20 16:34:21 +000011873 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011874 unsigned KnownAlign =
11875 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011876 if (KnownAlign >
11877 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11878 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011879 SI.setAlignment(KnownAlign);
11880
Dale Johannesenacb51a32009-03-03 01:43:03 +000011881 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011882 // stores to the same location, separated by a few arithmetic operations. This
11883 // situation often occurs with bitfield accesses.
11884 BasicBlock::iterator BBI = &SI;
11885 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11886 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011887 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011888 // Don't count debug info directives, lest they affect codegen,
11889 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11890 // It is necessary for correctness to skip those that feed into a
11891 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011892 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011893 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011894 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011895 continue;
11896 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011897
11898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11899 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011900 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11901 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011902 ++NumDeadStore;
11903 ++BBI;
11904 EraseInstFromFunction(*PrevSI);
11905 continue;
11906 }
11907 break;
11908 }
11909
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011910 // If this is a load, we have to stop. However, if the loaded value is from
11911 // the pointer we're loading and is producing the pointer we're storing,
11912 // then *this* store is dead (X = load P; store X -> P).
11913 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011914 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11915 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011916 EraseInstFromFunction(SI);
11917 ++NumCombined;
11918 return 0;
11919 }
11920 // Otherwise, this is a load from some other location. Stores before it
11921 // may not be dead.
11922 break;
11923 }
11924
Chris Lattner9ca96412006-02-08 03:25:32 +000011925 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011926 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011927 break;
11928 }
11929
11930
11931 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011932
11933 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011934 if (isa<ConstantPointerNull>(Ptr) &&
11935 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011936 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011937 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011938 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011939 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011940 ++NumCombined;
11941 }
11942 return 0; // Do not modify these!
11943 }
11944
11945 // store undef, Ptr -> noop
11946 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011947 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011948 ++NumCombined;
11949 return 0;
11950 }
11951
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011952 // If the pointer destination is a cast, see if we can fold the cast into the
11953 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011954 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11956 return Res;
11957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011958 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11960 return Res;
11961
Chris Lattner408902b2005-09-12 23:23:25 +000011962
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011963 // If this store is the last instruction in the basic block (possibly
11964 // excepting debug info instructions and the pointer bitcasts that feed
11965 // into them), and if the block ends with an unconditional branch, try
11966 // to move it to the successor block.
11967 BBI = &SI;
11968 do {
11969 ++BBI;
11970 } while (isa<DbgInfoIntrinsic>(BBI) ||
11971 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011972 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973 if (BI->isUnconditional())
11974 if (SimplifyStoreAtEndOfBlock(SI))
11975 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011976
Chris Lattner2f503e62005-01-31 05:36:43 +000011977 return 0;
11978}
11979
Chris Lattner3284d1f2007-04-15 00:07:55 +000011980/// SimplifyStoreAtEndOfBlock - Turn things like:
11981/// if () { *P = v1; } else { *P = v2 }
11982/// into a phi node with a store in the successor.
11983///
Chris Lattner31755a02007-04-15 01:02:18 +000011984/// Simplify things like:
11985/// *P = v1; if () { *P = v2; }
11986/// into a phi node with a store in the successor.
11987///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11989 BasicBlock *StoreBB = SI.getParent();
11990
11991 // Check to see if the successor block has exactly two incoming edges. If
11992 // so, see if the other predecessor contains a store to the same location.
11993 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011994 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995
11996 // Determine whether Dest has exactly two predecessors and, if so, compute
11997 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011998 pred_iterator PI = pred_begin(DestBB);
11999 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012000 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012001 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012002 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012003 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012004 return false;
12005
12006 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012007 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012009 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010 }
Chris Lattner31755a02007-04-15 01:02:18 +000012011 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012012 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012013
12014 // Bail out if all the relevant blocks aren't distinct (this can happen,
12015 // for example, if SI is in an infinite loop)
12016 if (StoreBB == DestBB || OtherBB == DestBB)
12017 return false;
12018
Chris Lattner31755a02007-04-15 01:02:18 +000012019 // Verify that the other block ends in a branch and is not otherwise empty.
12020 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012022 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012023 return false;
12024
Chris Lattner31755a02007-04-15 01:02:18 +000012025 // If the other block ends in an unconditional branch, check for the 'if then
12026 // else' case. there is an instruction before the branch.
12027 StoreInst *OtherStore = 0;
12028 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012029 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012030 // Skip over debugging info.
12031 while (isa<DbgInfoIntrinsic>(BBI) ||
12032 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12033 if (BBI==OtherBB->begin())
12034 return false;
12035 --BBI;
12036 }
12037 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012038 OtherStore = dyn_cast<StoreInst>(BBI);
12039 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12040 return false;
12041 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012042 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012043 // destinations is StoreBB, then we have the if/then case.
12044 if (OtherBr->getSuccessor(0) != StoreBB &&
12045 OtherBr->getSuccessor(1) != StoreBB)
12046 return false;
12047
12048 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012049 // if/then triangle. See if there is a store to the same ptr as SI that
12050 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012051 for (;; --BBI) {
12052 // Check to see if we find the matching store.
12053 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12054 if (OtherStore->getOperand(1) != SI.getOperand(1))
12055 return false;
12056 break;
12057 }
Eli Friedman6903a242008-06-13 22:02:12 +000012058 // If we find something that may be using or overwriting the stored
12059 // value, or if we run out of instructions, we can't do the xform.
12060 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012061 BBI == OtherBB->begin())
12062 return false;
12063 }
12064
12065 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012066 // make sure nothing reads or overwrites the stored value in
12067 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012068 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12069 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012070 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012071 return false;
12072 }
12073 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012074
Chris Lattner31755a02007-04-15 01:02:18 +000012075 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012076 Value *MergedVal = OtherStore->getOperand(0);
12077 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012078 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012079 PN->reserveOperandSpace(2);
12080 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012081 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12082 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012083 }
12084
12085 // Advance to a place where it is safe to insert the new store and
12086 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012087 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012088 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12089 OtherStore->isVolatile()), *BBI);
12090
12091 // Nuke the old stores.
12092 EraseInstFromFunction(SI);
12093 EraseInstFromFunction(*OtherStore);
12094 ++NumCombined;
12095 return true;
12096}
12097
Chris Lattner2f503e62005-01-31 05:36:43 +000012098
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012099Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12100 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012101 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012102 BasicBlock *TrueDest;
12103 BasicBlock *FalseDest;
12104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12105 !isa<Constant>(X)) {
12106 // Swap Destinations and condition...
12107 BI.setCondition(X);
12108 BI.setSuccessor(0, FalseDest);
12109 BI.setSuccessor(1, TrueDest);
12110 return &BI;
12111 }
12112
Reid Spencere4d87aa2006-12-23 06:05:41 +000012113 // Cannonicalize fcmp_one -> fcmp_oeq
12114 FCmpInst::Predicate FPred; Value *Y;
12115 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12116 TrueDest, FalseDest)))
12117 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12118 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12119 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012120 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012121 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012122 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012123 // Swap Destinations and condition...
12124 BI.setCondition(NewSCC);
12125 BI.setSuccessor(0, FalseDest);
12126 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012127 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012128 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012129 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012130 return &BI;
12131 }
12132
12133 // Cannonicalize icmp_ne -> icmp_eq
12134 ICmpInst::Predicate IPred;
12135 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12136 TrueDest, FalseDest)))
12137 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12138 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12139 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12140 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012141 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012142 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012143 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012144 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012145 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012146 BI.setSuccessor(0, FalseDest);
12147 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012148 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012149 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012150 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012151 return &BI;
12152 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012153
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012154 return 0;
12155}
Chris Lattner0864acf2002-11-04 16:18:53 +000012156
Chris Lattner46238a62004-07-03 00:26:11 +000012157Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12158 Value *Cond = SI.getCondition();
12159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12160 if (I->getOpcode() == Instruction::Add)
12161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012164 SI.setOperand(i,
12165 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012166 AddRHS));
12167 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012168 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012169 return &SI;
12170 }
12171 }
12172 return 0;
12173}
12174
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012175Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012176 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012177
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012178 if (!EV.hasIndices())
12179 return ReplaceInstUsesWith(EV, Agg);
12180
12181 if (Constant *C = dyn_cast<Constant>(Agg)) {
12182 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012183 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012184
12185 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012186 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012187
12188 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12189 // Extract the element indexed by the first index out of the constant
12190 Value *V = C->getOperand(*EV.idx_begin());
12191 if (EV.getNumIndices() > 1)
12192 // Extract the remaining indices out of the constant indexed by the
12193 // first index
12194 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12195 else
12196 return ReplaceInstUsesWith(EV, V);
12197 }
12198 return 0; // Can't handle other constants
12199 }
12200 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12201 // We're extracting from an insertvalue instruction, compare the indices
12202 const unsigned *exti, *exte, *insi, *inse;
12203 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12204 exte = EV.idx_end(), inse = IV->idx_end();
12205 exti != exte && insi != inse;
12206 ++exti, ++insi) {
12207 if (*insi != *exti)
12208 // The insert and extract both reference distinctly different elements.
12209 // This means the extract is not influenced by the insert, and we can
12210 // replace the aggregate operand of the extract with the aggregate
12211 // operand of the insert. i.e., replace
12212 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12213 // %E = extractvalue { i32, { i32 } } %I, 0
12214 // with
12215 // %E = extractvalue { i32, { i32 } } %A, 0
12216 return ExtractValueInst::Create(IV->getAggregateOperand(),
12217 EV.idx_begin(), EV.idx_end());
12218 }
12219 if (exti == exte && insi == inse)
12220 // Both iterators are at the end: Index lists are identical. Replace
12221 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12222 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12223 // with "i32 42"
12224 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12225 if (exti == exte) {
12226 // The extract list is a prefix of the insert list. i.e. replace
12227 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12228 // %E = extractvalue { i32, { i32 } } %I, 1
12229 // with
12230 // %X = extractvalue { i32, { i32 } } %A, 1
12231 // %E = insertvalue { i32 } %X, i32 42, 0
12232 // by switching the order of the insert and extract (though the
12233 // insertvalue should be left in, since it may have other uses).
12234 Value *NewEV = InsertNewInstBefore(
12235 ExtractValueInst::Create(IV->getAggregateOperand(),
12236 EV.idx_begin(), EV.idx_end()),
12237 EV);
12238 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12239 insi, inse);
12240 }
12241 if (insi == inse)
12242 // The insert list is a prefix of the extract list
12243 // We can simply remove the common indices from the extract and make it
12244 // operate on the inserted value instead of the insertvalue result.
12245 // i.e., replace
12246 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12247 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12248 // with
12249 // %E extractvalue { i32 } { i32 42 }, 0
12250 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12251 exti, exte);
12252 }
12253 // Can't simplify extracts from other values. Note that nested extracts are
12254 // already simplified implicitely by the above (extract ( extract (insert) )
12255 // will be translated into extract ( insert ( extract ) ) first and then just
12256 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012257 return 0;
12258}
12259
Chris Lattner220b0cf2006-03-05 00:22:33 +000012260/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12261/// is to leave as a vector operation.
12262static bool CheapToScalarize(Value *V, bool isConstant) {
12263 if (isa<ConstantAggregateZero>(V))
12264 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012265 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012266 if (isConstant) return true;
12267 // If all elts are the same, we can extract.
12268 Constant *Op0 = C->getOperand(0);
12269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12270 if (C->getOperand(i) != Op0)
12271 return false;
12272 return true;
12273 }
12274 Instruction *I = dyn_cast<Instruction>(V);
12275 if (!I) return false;
12276
12277 // Insert element gets simplified to the inserted element or is deleted if
12278 // this is constant idx extract element and its a constant idx insertelt.
12279 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12280 isa<ConstantInt>(I->getOperand(2)))
12281 return true;
12282 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12283 return true;
12284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12285 if (BO->hasOneUse() &&
12286 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12287 CheapToScalarize(BO->getOperand(1), isConstant)))
12288 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012289 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12290 if (CI->hasOneUse() &&
12291 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12292 CheapToScalarize(CI->getOperand(1), isConstant)))
12293 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012294
12295 return false;
12296}
12297
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012298/// Read and decode a shufflevector mask.
12299///
12300/// It turns undef elements into values that are larger than the number of
12301/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012302static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12303 unsigned NElts = SVI->getType()->getNumElements();
12304 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12305 return std::vector<unsigned>(NElts, 0);
12306 if (isa<UndefValue>(SVI->getOperand(2)))
12307 return std::vector<unsigned>(NElts, 2*NElts);
12308
12309 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012310 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012311 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12312 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012313 Result.push_back(NElts*2); // undef -> 8
12314 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012315 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012316 return Result;
12317}
12318
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012319/// FindScalarElement - Given a vector and an element number, see if the scalar
12320/// value is already around as a register, for example if it were inserted then
12321/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012322static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012323 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012324 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12325 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012326 unsigned Width = PTy->getNumElements();
12327 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012328 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012329
12330 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012331 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012332 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012333 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012334 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012335 return CP->getOperand(EltNo);
12336 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12337 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012338 if (!isa<ConstantInt>(III->getOperand(2)))
12339 return 0;
12340 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012341
12342 // If this is an insert to the element we are looking for, return the
12343 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012344 if (EltNo == IIElt)
12345 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012346
12347 // Otherwise, the insertelement doesn't modify the value, recurse on its
12348 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012349 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012350 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012351 unsigned LHSWidth =
12352 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012353 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012354 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012356 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012357 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012358 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012360 }
12361
12362 // Otherwise, we don't know.
12363 return 0;
12364}
12365
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012366Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012367 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012368 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012369 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012370
Dan Gohman07a96762007-07-16 14:29:03 +000012371 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012372 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012373 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012374
Reid Spencer9d6565a2007-02-15 02:26:10 +000012375 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012376 // If vector val is constant with all elements the same, replace EI with
12377 // that element. When the elements are not identical, we cannot replace yet
12378 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012379 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012380 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012381 if (C->getOperand(i) != op0) {
12382 op0 = 0;
12383 break;
12384 }
12385 if (op0)
12386 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012387 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012388
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012389 // If extracting a specified index from the vector, see if we can recursively
12390 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012391 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012392 unsigned IndexVal = IdxC->getZExtValue();
12393 unsigned VectorWidth =
12394 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12395
12396 // If this is extracting an invalid index, turn this into undef, to avoid
12397 // crashing the code below.
12398 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012399 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012400
Chris Lattner867b99f2006-10-05 06:55:50 +000012401 // This instruction only demands the single element from the input vector.
12402 // If the input vector has a single use, simplify it based on this use
12403 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012404 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012405 APInt UndefElts(VectorWidth, 0);
12406 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012407 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012408 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012409 EI.setOperand(0, V);
12410 return &EI;
12411 }
12412 }
12413
Owen Andersond672ecb2009-07-03 00:17:18 +000012414 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012415 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012416
12417 // If the this extractelement is directly using a bitcast from a vector of
12418 // the same number of elements, see if we can find the source element from
12419 // it. In this case, we will end up needing to bitcast the scalars.
12420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12421 if (const VectorType *VT =
12422 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12423 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012424 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12425 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012426 return new BitCastInst(Elt, EI.getType());
12427 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012428 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012429
Chris Lattner73fa49d2006-05-25 22:53:38 +000012430 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012431 if (I->hasOneUse()) {
12432 // Push extractelement into predecessor operation if legal and
12433 // profitable to do so
12434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012435 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12436 if (CheapToScalarize(BO, isConstantElt)) {
12437 ExtractElementInst *newEI0 =
12438 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12439 EI.getName()+".lhs");
12440 ExtractElementInst *newEI1 =
12441 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12442 EI.getName()+".rhs");
12443 InsertNewInstBefore(newEI0, EI);
12444 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012445 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012446 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012447 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012448 unsigned AS =
12449 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012450 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012451 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012452 GetElementPtrInst *GEP =
12453 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012454 InsertNewInstBefore(GEP, EI);
12455 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012456 }
12457 }
12458 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12459 // Extracting the inserted element?
12460 if (IE->getOperand(2) == EI.getOperand(1))
12461 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12462 // If the inserted and extracted elements are constants, they must not
12463 // be the same value, extract from the pre-inserted value instead.
12464 if (isa<Constant>(IE->getOperand(2)) &&
12465 isa<Constant>(EI.getOperand(1))) {
12466 AddUsesToWorkList(EI);
12467 EI.setOperand(0, IE->getOperand(0));
12468 return &EI;
12469 }
12470 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12471 // If this is extracting an element from a shufflevector, figure out where
12472 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012473 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12474 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012475 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012476 unsigned LHSWidth =
12477 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12478
12479 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012480 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012481 else if (SrcIdx < LHSWidth*2) {
12482 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012483 Src = SVI->getOperand(1);
12484 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012485 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012486 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012487 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012488 }
12489 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012490 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012491 return 0;
12492}
12493
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012494/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12495/// elements from either LHS or RHS, return the shuffle mask and true.
12496/// Otherwise, return false.
12497static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012498 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012499 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012500 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12501 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012502 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012503
12504 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012505 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012506 return true;
12507 } else if (V == LHS) {
12508 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012509 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510 return true;
12511 } else if (V == RHS) {
12512 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012513 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012514 return true;
12515 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12516 // If this is an insert of an extract from some other vector, include it.
12517 Value *VecOp = IEI->getOperand(0);
12518 Value *ScalarOp = IEI->getOperand(1);
12519 Value *IdxOp = IEI->getOperand(2);
12520
Chris Lattnerd929f062006-04-27 21:14:21 +000012521 if (!isa<ConstantInt>(IdxOp))
12522 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012523 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012524
12525 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12526 // Okay, we can handle this if the vector we are insertinting into is
12527 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012528 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012529 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012530 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012531 return true;
12532 }
12533 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12534 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012535 EI->getOperand(0)->getType() == V->getType()) {
12536 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012537 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012538
12539 // This must be extracting from either LHS or RHS.
12540 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12541 // Okay, we can handle this if the vector we are insertinting into is
12542 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012543 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012544 // If so, update the mask to reflect the inserted value.
12545 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012546 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012547 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012548 } else {
12549 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012550 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012551 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012552
12553 }
12554 return true;
12555 }
12556 }
12557 }
12558 }
12559 }
12560 // TODO: Handle shufflevector here!
12561
12562 return false;
12563}
12564
12565/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12566/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12567/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012568static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012569 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012570 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012571 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012572 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012573 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012574
12575 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012576 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012577 return V;
12578 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012579 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012580 return V;
12581 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12582 // If this is an insert of an extract from some other vector, include it.
12583 Value *VecOp = IEI->getOperand(0);
12584 Value *ScalarOp = IEI->getOperand(1);
12585 Value *IdxOp = IEI->getOperand(2);
12586
12587 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12588 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12589 EI->getOperand(0)->getType() == V->getType()) {
12590 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012591 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12592 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012593
12594 // Either the extracted from or inserted into vector must be RHSVec,
12595 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012596 if (EI->getOperand(0) == RHS || RHS == 0) {
12597 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012598 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012599 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012600 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012601 return V;
12602 }
12603
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012604 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012605 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12606 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012607 // Everything but the extracted element is replaced with the RHS.
12608 for (unsigned i = 0; i != NumElts; ++i) {
12609 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012610 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012611 }
12612 return V;
12613 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012614
12615 // If this insertelement is a chain that comes from exactly these two
12616 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012617 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12618 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012619 return EI->getOperand(0);
12620
Chris Lattnerefb47352006-04-15 01:39:45 +000012621 }
12622 }
12623 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012624 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012625
12626 // Otherwise, can't do anything fancy. Return an identity vector.
12627 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012628 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012629 return V;
12630}
12631
12632Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12633 Value *VecOp = IE.getOperand(0);
12634 Value *ScalarOp = IE.getOperand(1);
12635 Value *IdxOp = IE.getOperand(2);
12636
Chris Lattner599ded12007-04-09 01:11:16 +000012637 // Inserting an undef or into an undefined place, remove this.
12638 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12639 ReplaceInstUsesWith(IE, VecOp);
12640
Chris Lattnerefb47352006-04-15 01:39:45 +000012641 // If the inserted element was extracted from some other vector, and if the
12642 // indexes are constant, try to turn this into a shufflevector operation.
12643 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12644 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12645 EI->getOperand(0)->getType() == IE.getType()) {
12646 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012647 unsigned ExtractedIdx =
12648 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012649 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012650
12651 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12652 return ReplaceInstUsesWith(IE, VecOp);
12653
12654 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012655 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012656
12657 // If we are extracting a value from a vector, then inserting it right
12658 // back into the same place, just use the input vector.
12659 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12660 return ReplaceInstUsesWith(IE, VecOp);
12661
12662 // We could theoretically do this for ANY input. However, doing so could
12663 // turn chains of insertelement instructions into a chain of shufflevector
12664 // instructions, and right now we do not merge shufflevectors. As such,
12665 // only do this in a situation where it is clear that there is benefit.
12666 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12667 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12668 // the values of VecOp, except then one read from EIOp0.
12669 // Build a new shuffle mask.
12670 std::vector<Constant*> Mask;
12671 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012672 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012673 else {
12674 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012675 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012676 NumVectorElts));
12677 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012678 Mask[InsertedIdx] =
12679 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012680 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012681 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012682 }
12683
12684 // If this insertelement isn't used by some other insertelement, turn it
12685 // (and any insertelements it points to), into one big shuffle.
12686 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12687 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012688 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012689 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12690 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012691 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 return new ShuffleVectorInst(LHS, RHS,
12693 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012694 }
12695 }
12696 }
12697
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012698 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12699 APInt UndefElts(VWidth, 0);
12700 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12701 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12702 return &IE;
12703
Chris Lattnerefb47352006-04-15 01:39:45 +000012704 return 0;
12705}
12706
12707
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012708Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12709 Value *LHS = SVI.getOperand(0);
12710 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012711 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012712
12713 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012714
Chris Lattner867b99f2006-10-05 06:55:50 +000012715 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012716 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012717 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012718
Dan Gohman488fbfc2008-09-09 18:11:14 +000012719 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012720
12721 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12722 return 0;
12723
Evan Cheng388df622009-02-03 10:05:09 +000012724 APInt UndefElts(VWidth, 0);
12725 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12726 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012727 LHS = SVI.getOperand(0);
12728 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012729 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012730 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012731
Chris Lattner863bcff2006-05-25 23:48:38 +000012732 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12733 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12734 if (LHS == RHS || isa<UndefValue>(LHS)) {
12735 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012736 // shuffle(undef,undef,mask) -> undef.
12737 return ReplaceInstUsesWith(SVI, LHS);
12738 }
12739
Chris Lattner863bcff2006-05-25 23:48:38 +000012740 // Remap any references to RHS to use LHS.
12741 std::vector<Constant*> Elts;
12742 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012743 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012744 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012745 else {
12746 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012747 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012748 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012749 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012750 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012751 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012752 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012753 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012754 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012755 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012756 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012757 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12758 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012759 LHS = SVI.getOperand(0);
12760 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012761 MadeChange = true;
12762 }
12763
Chris Lattner7b2e27922006-05-26 00:29:06 +000012764 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012765 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012766
Chris Lattner863bcff2006-05-25 23:48:38 +000012767 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12768 if (Mask[i] >= e*2) continue; // Ignore undef values.
12769 // Is this an identity shuffle of the LHS value?
12770 isLHSID &= (Mask[i] == i);
12771
12772 // Is this an identity shuffle of the RHS value?
12773 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012774 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012775
Chris Lattner863bcff2006-05-25 23:48:38 +000012776 // Eliminate identity shuffles.
12777 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12778 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012779
Chris Lattner7b2e27922006-05-26 00:29:06 +000012780 // If the LHS is a shufflevector itself, see if we can combine it with this
12781 // one without producing an unusual shuffle. Here we are really conservative:
12782 // we are absolutely afraid of producing a shuffle mask not in the input
12783 // program, because the code gen may not be smart enough to turn a merged
12784 // shuffle into two specific shuffles: it may produce worse code. As such,
12785 // we only merge two shuffles if the result is one of the two input shuffle
12786 // masks. In this case, merging the shuffles just removes one instruction,
12787 // which we know is safe. This is good for things like turning:
12788 // (splat(splat)) -> splat.
12789 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12790 if (isa<UndefValue>(RHS)) {
12791 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12792
12793 std::vector<unsigned> NewMask;
12794 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12795 if (Mask[i] >= 2*e)
12796 NewMask.push_back(2*e);
12797 else
12798 NewMask.push_back(LHSMask[Mask[i]]);
12799
12800 // If the result mask is equal to the src shuffle or this shuffle mask, do
12801 // the replacement.
12802 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012803 unsigned LHSInNElts =
12804 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012805 std::vector<Constant*> Elts;
12806 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012807 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012808 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012809 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012810 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012811 }
12812 }
12813 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12814 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012815 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012816 }
12817 }
12818 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012819
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012820 return MadeChange ? &SVI : 0;
12821}
12822
12823
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012824
Chris Lattnerea1c4542004-12-08 23:43:58 +000012825
12826/// TryToSinkInstruction - Try to move the specified instruction from its
12827/// current block into the beginning of DestBlock, which can only happen if it's
12828/// safe to move the instruction past all of the instructions between it and the
12829/// end of its block.
12830static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12831 assert(I->hasOneUse() && "Invariants didn't hold!");
12832
Chris Lattner108e9022005-10-27 17:13:11 +000012833 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012834 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012835 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012836
Chris Lattnerea1c4542004-12-08 23:43:58 +000012837 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012838 if (isa<AllocaInst>(I) && I->getParent() ==
12839 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012840 return false;
12841
Chris Lattner96a52a62004-12-09 07:14:34 +000012842 // We can only sink load instructions if there is nothing between the load and
12843 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012844 if (I->mayReadFromMemory()) {
12845 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012846 Scan != E; ++Scan)
12847 if (Scan->mayWriteToMemory())
12848 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012849 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012850
Dan Gohman02dea8b2008-05-23 21:05:58 +000012851 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012852
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012853 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012854 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012855 ++NumSunkInst;
12856 return true;
12857}
12858
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012859
12860/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12861/// all reachable code to the worklist.
12862///
12863/// This has a couple of tricks to make the code faster and more powerful. In
12864/// particular, we constant fold and DCE instructions as we go, to avoid adding
12865/// them to the worklist (this significantly speeds up instcombine on code where
12866/// many instructions are dead or constant). Additionally, if we find a branch
12867/// whose condition is a known constant, we only visit the reachable successors.
12868///
12869static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012870 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012871 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012872 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012873 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012874 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012875
Chris Lattner2c7718a2007-03-23 19:17:18 +000012876 while (!Worklist.empty()) {
12877 BB = Worklist.back();
12878 Worklist.pop_back();
12879
12880 // We have now visited this block! If we've already been here, ignore it.
12881 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012882
12883 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012884 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12885 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012886
Chris Lattner2c7718a2007-03-23 19:17:18 +000012887 // DCE instruction if trivially dead.
12888 if (isInstructionTriviallyDead(Inst)) {
12889 ++NumDeadInst;
12890 DOUT << "IC: DCE: " << *Inst;
12891 Inst->eraseFromParent();
12892 continue;
12893 }
12894
12895 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012896 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012897 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12898 Inst->replaceAllUsesWith(C);
12899 ++NumConstProp;
12900 Inst->eraseFromParent();
12901 continue;
12902 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012903
Devang Patel7fe1dec2008-11-19 18:56:50 +000012904 // If there are two consecutive llvm.dbg.stoppoint calls then
12905 // it is likely that the optimizer deleted code in between these
12906 // two intrinsics.
12907 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12908 if (DBI_Next) {
12909 if (DBI_Prev
12910 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12911 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12912 IC.RemoveFromWorkList(DBI_Prev);
12913 DBI_Prev->eraseFromParent();
12914 }
12915 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012916 } else {
12917 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012918 }
12919
Chris Lattner2c7718a2007-03-23 19:17:18 +000012920 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012921 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012922
12923 // Recursively visit successors. If this is a branch or switch on a
12924 // constant, only visit the reachable successor.
12925 TerminatorInst *TI = BB->getTerminator();
12926 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12927 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12928 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012929 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012930 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012931 continue;
12932 }
12933 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12934 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12935 // See if this is an explicit destination.
12936 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12937 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012938 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012939 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012940 continue;
12941 }
12942
12943 // Otherwise it is the default destination.
12944 Worklist.push_back(SI->getSuccessor(0));
12945 continue;
12946 }
12947 }
12948
12949 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12950 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012951 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012952}
12953
Chris Lattnerec9c3582007-03-03 02:04:50 +000012954bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012955 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012956 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012957
12958 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12959 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012960
Chris Lattnerb3d59702005-07-07 20:40:38 +000012961 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012962 // Do a depth-first traversal of the function, populate the worklist with
12963 // the reachable instructions. Ignore blocks that are not reachable. Keep
12964 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012965 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012966 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012967
Chris Lattnerb3d59702005-07-07 20:40:38 +000012968 // Do a quick scan over the function. If we find any blocks that are
12969 // unreachable, remove any instructions inside of them. This prevents
12970 // the instcombine code from having to deal with some bad special cases.
12971 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12972 if (!Visited.count(BB)) {
12973 Instruction *Term = BB->getTerminator();
12974 while (Term != BB->begin()) { // Remove instrs bottom-up
12975 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012976
Bill Wendlingb7427032006-11-26 09:46:52 +000012977 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012978 // A debug intrinsic shouldn't force another iteration if we weren't
12979 // going to do one without it.
12980 if (!isa<DbgInfoIntrinsic>(I)) {
12981 ++NumDeadInst;
12982 Changed = true;
12983 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012984 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012985 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012986 I->eraseFromParent();
12987 }
12988 }
12989 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012990
Chris Lattnerdbab3862007-03-02 21:28:56 +000012991 while (!Worklist.empty()) {
12992 Instruction *I = RemoveOneFromWorkList();
12993 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012994
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012995 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012996 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012997 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012998 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012999 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000013000 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013001
Bill Wendlingb7427032006-11-26 09:46:52 +000013002 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013003
13004 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013005 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013006 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013007 continue;
13008 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013009
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013010 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013011 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013012 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013013
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013014 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013015 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013016 ReplaceInstUsesWith(*I, C);
13017
Chris Lattner62b14df2002-09-02 04:59:56 +000013018 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013019 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013020 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013021 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013022 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013023 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013024
Dan Gohman31e4c772009-05-07 19:43:39 +000013025 if (TD &&
13026 (I->getType()->getTypeID() == Type::VoidTyID ||
13027 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013028 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013029 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13030 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013031 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13032 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013033 if (NewC != CE) {
13034 i->set(NewC);
13035 Changed = true;
13036 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013037 }
13038
Chris Lattnerea1c4542004-12-08 23:43:58 +000013039 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013040 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013041 BasicBlock *BB = I->getParent();
13042 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13043 if (UserParent != BB) {
13044 bool UserIsSuccessor = false;
13045 // See if the user is one of our successors.
13046 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13047 if (*SI == UserParent) {
13048 UserIsSuccessor = true;
13049 break;
13050 }
13051
13052 // If the user is one of our immediate successors, and if that successor
13053 // only has us as a predecessors (we'd have to split the critical edge
13054 // otherwise), we can keep going.
13055 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13056 next(pred_begin(UserParent)) == pred_end(UserParent))
13057 // Okay, the CFG is simple enough, try to sink this instruction.
13058 Changed |= TryToSinkInstruction(I, UserParent);
13059 }
13060 }
13061
Chris Lattner8a2a3112001-12-14 16:52:21 +000013062 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013063#ifndef NDEBUG
13064 std::string OrigI;
13065#endif
13066 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013067 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013068 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013069 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013070 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013071 DOUT << "IC: Old = " << *I
13072 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013073
Chris Lattnerf523d062004-06-09 05:08:07 +000013074 // Everything uses the new instruction now.
13075 I->replaceAllUsesWith(Result);
13076
13077 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013078 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013079 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013080
Chris Lattner6934a042007-02-11 01:23:03 +000013081 // Move the name to the new instruction first.
13082 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013083
13084 // Insert the new instruction into the basic block...
13085 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013086 BasicBlock::iterator InsertPos = I;
13087
13088 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13089 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13090 ++InsertPos;
13091
13092 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013093
Chris Lattner00d51312004-05-01 23:27:23 +000013094 // Make sure that we reprocess all operands now that we reduced their
13095 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013096 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013097
Chris Lattnerf523d062004-06-09 05:08:07 +000013098 // Instructions can end up on the worklist more than once. Make sure
13099 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013100 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013101
13102 // Erase the old instruction.
13103 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013104 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013105#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013106 DOUT << "IC: Mod = " << OrigI
13107 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013108#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013109
Chris Lattner90ac28c2002-08-02 19:29:35 +000013110 // If the instruction was modified, it's possible that it is now dead.
13111 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013112 if (isInstructionTriviallyDead(I)) {
13113 // Make sure we process all operands now that we are reducing their
13114 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013115 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013116
Chris Lattner00d51312004-05-01 23:27:23 +000013117 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013118 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013119 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013120 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013121 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013122 AddToWorkList(I);
13123 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013124 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013125 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013126 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013127 }
13128 }
13129
Chris Lattnerec9c3582007-03-03 02:04:50 +000013130 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013131
13132 // Do an explicit clear, this shrinks the map if needed.
13133 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013134 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013135}
13136
Chris Lattnerec9c3582007-03-03 02:04:50 +000013137
13138bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013139 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13140
Chris Lattnerec9c3582007-03-03 02:04:50 +000013141 bool EverMadeChange = false;
13142
13143 // Iterate while there is work to do.
13144 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013145 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013146 EverMadeChange = true;
13147 return EverMadeChange;
13148}
13149
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013150FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013151 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013152}