blob: 4a777b331b9dd6256a1ee146f0122045d997aece [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000058#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000059#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000060#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000062#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000063#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000064#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000065#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000066using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000067using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000074
Chris Lattner0e5f4992006-12-19 21:40:18 +000075namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000076 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000080 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000082 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000083 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000085 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000086 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000087
Owen Andersone922c022009-07-22 00:24:57 +000088 LLVMContext *Context;
89 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000090
Chris Lattnerdbab3862007-03-02 21:28:56 +000091 /// AddToWorkList - Add the specified instruction to the worklist if it
92 /// isn't already in it.
93 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000095 Worklist.push_back(I);
96 }
97
98 // RemoveFromWorkList - remove I from the worklist if it exists.
99 void RemoveFromWorkList(Instruction *I) {
100 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
101 if (It == WorklistMap.end()) return; // Not in worklist.
102
103 // Don't bother moving everything down, just null out the slot.
104 Worklist[It->second] = 0;
105
106 WorklistMap.erase(It);
107 }
108
109 Instruction *RemoveOneFromWorkList() {
110 Instruction *I = Worklist.back();
111 Worklist.pop_back();
112 WorklistMap.erase(I);
113 return I;
114 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000117 /// AddUsersToWorkList - When an instruction is simplified, add all users of
118 /// the instruction to the work lists because they might get more simplified
119 /// now.
120 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000121 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000122 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000124 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000125 }
126
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 /// AddUsesToWorkList - When an instruction is simplified, add operands to
128 /// the work lists because they might get more simplified now.
129 ///
130 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000131 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
132 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000133 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000134 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000135
136 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
137 /// dead. Add all of its operands to the worklist, turning them into
138 /// undef's to reduce the number of uses of those instructions.
139 ///
140 /// Return the specified operand before it is turned into an undef.
141 ///
142 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
143 Value *R = I.getOperand(op);
144
Gabor Greif177dd3f2008-06-12 21:37:33 +0000145 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
146 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000147 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000148 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000149 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000150 }
151
152 return R;
153 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000154
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000155 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000156 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000157
158 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159
Chris Lattner97e52e42002-04-28 21:27:06 +0000160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000161 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000162 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000163 }
164
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000165 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000166
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000171 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 //
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000192 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000193 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000194 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000195 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000196 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000197 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000198 Instruction *visitOr (BinaryOperator &I);
199 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000200 Instruction *visitShl(BinaryOperator &I);
201 Instruction *visitAShr(BinaryOperator &I);
202 Instruction *visitLShr(BinaryOperator &I);
203 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000204 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
205 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000206 Instruction *visitFCmpInst(FCmpInst &I);
207 Instruction *visitICmpInst(ICmpInst &I);
208 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000209 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
210 Instruction *LHS,
211 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000212 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
213 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000214
Reid Spencere4d87aa2006-12-23 06:05:41 +0000215 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
216 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000217 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000218 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *commonCastTransforms(CastInst &CI);
220 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000221 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000222 Instruction *visitTrunc(TruncInst &CI);
223 Instruction *visitZExt(ZExtInst &CI);
224 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000225 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000227 Instruction *visitFPToUI(FPToUIInst &FI);
228 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000229 Instruction *visitUIToFP(CastInst &CI);
230 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000231 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000232 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000233 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000234 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
235 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000236 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000237 Instruction *visitSelectInst(SelectInst &SI);
238 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000239 Instruction *visitCallInst(CallInst &CI);
240 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000241 Instruction *visitPHINode(PHINode &PN);
242 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000243 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000244 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000245 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000246 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000247 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000248 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000249 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000250 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000251 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000252 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000253
254 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000255 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000256
Chris Lattner9fe38862003-06-19 17:00:31 +0000257 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000258 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000259 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000260 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000261 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
262 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000263 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000264 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
265
Chris Lattner9fe38862003-06-19 17:00:31 +0000266
Chris Lattner28977af2004-04-05 01:30:19 +0000267 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000268 // InsertNewInstBefore - insert an instruction New before instruction Old
269 // in the program. Add the new instruction to the worklist.
270 //
Chris Lattner955f3312004-09-28 21:48:02 +0000271 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000272 assert(New && New->getParent() == 0 &&
273 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000274 BasicBlock *BB = Old.getParent();
275 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000276 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000277 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000278 }
279
Chris Lattner0c967662004-09-24 15:21:34 +0000280 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
281 /// This also adds the cast to the worklist. Finally, this returns the
282 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000283 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
284 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000285 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000286
Chris Lattnere2ed0572006-04-06 19:19:17 +0000287 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000288 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000289
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000290 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000291 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000292 return C;
293 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000294
295 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
296 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
297 }
298
Chris Lattner0c967662004-09-24 15:21:34 +0000299
Chris Lattner8b170942002-08-09 23:47:40 +0000300 // ReplaceInstUsesWith - This method is to be used when an instruction is
301 // found to be dead, replacable with another preexisting expression. Here
302 // we add all uses of I to the worklist, replace all uses of I with the new
303 // value, then return I, so that the inst combiner will know that I was
304 // modified.
305 //
306 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000307 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000308 if (&I != V) {
309 I.replaceAllUsesWith(V);
310 return &I;
311 } else {
312 // If we are replacing the instruction with itself, this must be in a
313 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000314 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000315 return &I;
316 }
Chris Lattner8b170942002-08-09 23:47:40 +0000317 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318
319 // EraseInstFromFunction - When dealing with an instruction that has side
320 // effects or produces a void value, we can't rely on DCE to delete the
321 // instruction. Instead, visit methods should return the value returned by
322 // this function.
323 Instruction *EraseInstFromFunction(Instruction &I) {
324 assert(I.use_empty() && "Cannot erase instruction that is used!");
325 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000326 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000327 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000328 return 0; // Don't do anything with FI
329 }
Chris Lattner173234a2008-06-02 01:18:21 +0000330
331 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
332 APInt &KnownOne, unsigned Depth = 0) const {
333 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 }
335
336 bool MaskedValueIsZero(Value *V, const APInt &Mask,
337 unsigned Depth = 0) const {
338 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 }
340 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
341 return llvm::ComputeNumSignBits(Op, TD, Depth);
342 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000343
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000344 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000345
Reid Spencere4d87aa2006-12-23 06:05:41 +0000346 /// SimplifyCommutative - This performs a few simplifications for
347 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000348 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000349
Reid Spencere4d87aa2006-12-23 06:05:41 +0000350 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
351 /// most-complex to least-complex order.
352 bool SimplifyCompare(CmpInst &I);
353
Chris Lattner886ab6c2009-01-31 08:15:18 +0000354 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
355 /// based on the demanded bits.
356 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
357 APInt& KnownZero, APInt& KnownOne,
358 unsigned Depth);
359 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000360 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000361 unsigned Depth=0);
362
363 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
364 /// SimplifyDemandedBits knows about. See if the instruction has any
365 /// properties that allow us to simplify its operands.
366 bool SimplifyDemandedInstructionBits(Instruction &Inst);
367
Evan Cheng388df622009-02-03 10:05:09 +0000368 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
369 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000370
Chris Lattner4e998b22004-09-29 05:07:12 +0000371 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
372 // PHI node as operand #0, see if we can fold the instruction into the PHI
373 // (which is only possible if all operands to the PHI are constants).
374 Instruction *FoldOpIntoPhi(Instruction &I);
375
Chris Lattnerbac32862004-11-14 19:13:23 +0000376 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
377 // operator and they all are only used by the PHI, PHI together their
378 // inputs, and do the operation once, to the result of the PHI.
379 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000380 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000381 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
382
Chris Lattner7da52b22006-11-01 04:51:18 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
385 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000387 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000388 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000389 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000390 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000391 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000392 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000393 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000395 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000396
Chris Lattnerafe91a52006-06-15 19:07:26 +0000397
Reid Spencerc55b2432006-12-13 18:21:21 +0000398 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000399
Dan Gohman6de29f82009-06-15 22:12:54 +0000400 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000401 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000402 unsigned GetOrEnforceKnownAlignment(Value *V,
403 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000404
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000405 };
406}
407
Dan Gohman844731a2008-05-13 00:00:25 +0000408char InstCombiner::ID = 0;
409static RegisterPass<InstCombiner>
410X("instcombine", "Combine redundant instructions");
411
Chris Lattner4f98c562003-03-10 21:43:22 +0000412// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000413// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000414static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000415 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000416 if (BinaryOperator::isNeg(V) ||
417 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000418 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000419 return 3;
420 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000421 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000422 if (isa<Argument>(V)) return 3;
423 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000424}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000425
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426// isOnlyUse - Return true if this instruction will be deleted if we stop using
427// it.
428static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000429 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000430}
431
Chris Lattner4cb170c2004-02-23 06:38:22 +0000432// getPromotedType - Return the specified type promoted as it would be to pass
433// though a va_arg area...
434static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000435 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
436 if (ITy->getBitWidth() < 32)
437 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000438 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000439 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000440}
441
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442/// getBitCastOperand - If the specified operand is a CastInst, a constant
443/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
444/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000445static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000446 if (Operator *O = dyn_cast<Operator>(V)) {
447 if (O->getOpcode() == Instruction::BitCast)
448 return O->getOperand(0);
449 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
450 if (GEP->hasAllZeroIndices())
451 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000452 }
Chris Lattnereed48272005-09-13 00:40:14 +0000453 return 0;
454}
455
Reid Spencer3da59db2006-11-27 01:05:10 +0000456/// This function is a wrapper around CastInst::isEliminableCastPair. It
457/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000458static Instruction::CastOps
459isEliminableCastPair(
460 const CastInst *CI, ///< The first cast instruction
461 unsigned opcode, ///< The opcode of the second cast instruction
462 const Type *DstTy, ///< The target type for the second cast instruction
463 TargetData *TD ///< The target data for pointer size
464) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000465
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
467 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000468
Reid Spencer3da59db2006-11-27 01:05:10 +0000469 // Get the opcodes of the two Cast instructions
470 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
471 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000472
Chris Lattnera0e69692009-03-24 18:35:40 +0000473 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000474 DstTy,
475 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000476
477 // We don't want to form an inttoptr or ptrtoint that converts to an integer
478 // type that differs from the pointer size.
479 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
480 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
481 Res = 0;
482
483 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000484}
485
486/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
487/// in any code being generated. It does not require codegen if V is simple
488/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
490 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000491 if (V->getType() == Ty || isa<Constant>(V)) return false;
492
Chris Lattner01575b72006-05-25 23:24:33 +0000493 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000494 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000495 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000496 return false;
497 return true;
498}
499
Chris Lattner4f98c562003-03-10 21:43:22 +0000500// SimplifyCommutative - This performs a few simplifications for commutative
501// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000502//
Chris Lattner4f98c562003-03-10 21:43:22 +0000503// 1. Order operands such that they are listed from right (least complex) to
504// left (most complex). This puts constants before unary operators before
505// binary operators.
506//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
508// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000509//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000512 if (getComplexity(Context, I.getOperand(0)) <
513 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000515
Chris Lattner4f98c562003-03-10 21:43:22 +0000516 if (!I.isAssociative()) return Changed;
517 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
519 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
520 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000521 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000522 cast<Constant>(I.getOperand(1)),
523 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524 I.setOperand(0, Op->getOperand(0));
525 I.setOperand(1, Folded);
526 return true;
527 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
528 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
529 isOnlyUse(Op) && isOnlyUse(Op1)) {
530 Constant *C1 = cast<Constant>(Op->getOperand(1));
531 Constant *C2 = cast<Constant>(Op1->getOperand(1));
532
533 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000534 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000535 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 Op1->getOperand(0),
537 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000538 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000539 I.setOperand(0, New);
540 I.setOperand(1, Folded);
541 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000542 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000543 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000545}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000546
Reid Spencere4d87aa2006-12-23 06:05:41 +0000547/// SimplifyCompare - For a CmpInst this function just orders the operands
548/// so that theyare listed from right (least complex) to left (most complex).
549/// This puts constants before unary operators before binary operators.
550bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000551 if (getComplexity(Context, I.getOperand(0)) >=
552 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000553 return false;
554 I.swapOperands();
555 // Compare instructions are not associative so there's nothing else we can do.
556 return true;
557}
558
Chris Lattner8d969642003-03-10 23:06:50 +0000559// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
560// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000561//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000562static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000563 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000564 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000565
Chris Lattner0ce85802004-12-14 20:08:06 +0000566 // Constants can be considered to be negated values if they can be folded.
567 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000568 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000569
570 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
571 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000572 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000573
Chris Lattner8d969642003-03-10 23:06:50 +0000574 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000575}
576
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000577// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
578// instruction if the LHS is a constant negative zero (which is the 'negate'
579// form).
580//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000581static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000582 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000583 return BinaryOperator::getFNegArgument(V);
584
585 // Constants can be considered to be negated values if they can be folded.
586 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000587 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000588
589 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
590 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000591 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000592
593 return 0;
594}
595
Owen Anderson07cf79e2009-07-06 23:00:19 +0000596static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000597 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000598 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000599
600 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000601 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersoneed707b2009-07-24 23:12:02 +0000602 return ConstantInt::get(*Context, ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000603 return 0;
604}
605
Chris Lattnerc8802d22003-03-11 00:12:48 +0000606// dyn_castFoldableMul - If this value is a multiply that can be folded into
607// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000608// non-constant operand of the multiply, and set CST to point to the multiplier.
609// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000610//
Owen Andersond672ecb2009-07-03 00:17:18 +0000611static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000612 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000617 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000618 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000620 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +0000623 CST = ConstantInt::get(*Context, APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000624 return I->getOperand(0);
625 }
626 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000627 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000628}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000629
Chris Lattner574da9b2005-01-13 20:14:25 +0000630/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
631/// expression, return it.
632static User *dyn_castGetElementPtr(Value *V) {
633 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
635 if (CE->getOpcode() == Instruction::GetElementPtr)
636 return cast<User>(V);
637 return false;
638}
639
Reid Spencer7177c3a2007-03-25 05:33:51 +0000640/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000641static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000642 return Context->getConstantExprAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000643 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000644}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000645/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000646static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000647 return Context->getConstantExprSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000648 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000649}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000650/// MultiplyOverflows - True if the multiply can not be expressed in an int
651/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000652static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000653 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000654 uint32_t W = C1->getBitWidth();
655 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656 if (sign) {
657 LHSExt.sext(W * 2);
658 RHSExt.sext(W * 2);
659 } else {
660 LHSExt.zext(W * 2);
661 RHSExt.zext(W * 2);
662 }
663
664 APInt MulExt = LHSExt * RHSExt;
665
666 if (sign) {
667 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669 return MulExt.slt(Min) || MulExt.sgt(Max);
670 } else
671 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672}
Chris Lattner955f3312004-09-28 21:48:02 +0000673
Reid Spencere7816b52007-03-08 01:52:58 +0000674
Chris Lattner255d8912006-02-11 09:31:47 +0000675/// ShrinkDemandedConstant - Check to see if the specified operand of the
676/// specified instruction is a constant integer. If so, check to see if there
677/// are any bits set in the constant that are not demanded. If so, shrink the
678/// constant and return true.
679static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000680 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000681 assert(I && "No instruction?");
682 assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684 // If the operand is not a constant integer, nothing to do.
685 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686 if (!OpC) return false;
687
688 // If there are no bits set that aren't demanded, nothing to do.
689 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690 if ((~Demanded & OpC->getValue()) == 0)
691 return false;
692
693 // This instruction is producing bits that are not demanded. Shrink the RHS.
694 Demanded &= OpC->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +0000695 I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000696 return true;
697}
698
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000699// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
700// set of known zero and one bits, compute the maximum and minimum values that
701// could have the specified known zero and known one bits, returning them in
702// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000703static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000704 const APInt& KnownOne,
705 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000706 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
707 KnownZero.getBitWidth() == Min.getBitWidth() &&
708 KnownZero.getBitWidth() == Max.getBitWidth() &&
709 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000710 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717 if (UnknownBits.isNegative()) { // Sign bit is unknown
718 Min.set(Min.getBitWidth()-1);
719 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000728 const APInt &KnownOne,
729 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731 KnownZero.getBitWidth() == Min.getBitWidth() &&
732 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000733 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000734 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000735
736 // The minimum value is when the unknown bits are all zeros.
737 Min = KnownOne;
738 // The maximum value is when the unknown bits are all ones.
739 Max = KnownOne|UnknownBits;
740}
Chris Lattner255d8912006-02-11 09:31:47 +0000741
Chris Lattner886ab6c2009-01-31 08:15:18 +0000742/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
743/// SimplifyDemandedBits knows about. See if the instruction has any
744/// properties that allow us to simplify its operands.
745bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000746 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000747 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
748 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
749
750 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
751 KnownZero, KnownOne, 0);
752 if (V == 0) return false;
753 if (V == &Inst) return true;
754 ReplaceInstUsesWith(Inst, V);
755 return true;
756}
757
758/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
759/// specified instruction operand if possible, updating it in place. It returns
760/// true if it made any change and false otherwise.
761bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
762 APInt &KnownZero, APInt &KnownOne,
763 unsigned Depth) {
764 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
765 KnownZero, KnownOne, Depth);
766 if (NewVal == 0) return false;
767 U.set(NewVal);
768 return true;
769}
770
771
772/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
773/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000774/// that only the bits set in DemandedMask of the result of V are ever used
775/// downstream. Consequently, depending on the mask and V, it may be possible
776/// to replace V with a constant or one of its operands. In such cases, this
777/// function does the replacement and returns true. In all other cases, it
778/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000779/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000780/// to be zero in the expression. These are provided to potentially allow the
781/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
782/// the expression. KnownOne and KnownZero always follow the invariant that
783/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
784/// the bits in KnownOne and KnownZero may only be accurate for those bits set
785/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
786/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000787///
788/// This returns null if it did not change anything and it permits no
789/// simplification. This returns V itself if it did some simplification of V's
790/// operands based on the information about what bits are demanded. This returns
791/// some other non-null value if it found out that V is equal to another value
792/// in the context where the specified bits are demanded, but not for all users.
793Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
794 APInt &KnownZero, APInt &KnownOne,
795 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000796 assert(V != 0 && "Null pointer of Value???");
797 assert(Depth <= 6 && "Limit Search Depth");
798 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000799 const Type *VTy = V->getType();
800 assert((TD || !isa<PointerType>(VTy)) &&
801 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000802 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
803 (!VTy->isIntOrIntVector() ||
804 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000806 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000807 "Value *V, DemandedMask, KnownZero and KnownOne "
808 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000809 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
810 // We know all of the bits for a constant!
811 KnownOne = CI->getValue() & DemandedMask;
812 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000813 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000814 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000815 if (isa<ConstantPointerNull>(V)) {
816 // We know all of the bits for a constant!
817 KnownOne.clear();
818 KnownZero = DemandedMask;
819 return 0;
820 }
821
Chris Lattner08d2cc72009-01-31 07:26:06 +0000822 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000823 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000824 if (DemandedMask == 0) { // Not demanding any bits from V.
825 if (isa<UndefValue>(V))
826 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000827 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000828 }
829
Chris Lattner4598c942009-01-31 08:24:16 +0000830 if (Depth == 6) // Limit search depth.
831 return 0;
832
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000833 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
834 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
835
Dan Gohman1c8491e2009-04-25 17:12:48 +0000836 Instruction *I = dyn_cast<Instruction>(V);
837 if (!I) {
838 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
839 return 0; // Only analyze instructions.
840 }
841
Chris Lattner4598c942009-01-31 08:24:16 +0000842 // If there are multiple uses of this value and we aren't at the root, then
843 // we can't do any simplifications of the operands, because DemandedMask
844 // only reflects the bits demanded by *one* of the users.
845 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000846 // Despite the fact that we can't simplify this instruction in all User's
847 // context, we can at least compute the knownzero/knownone bits, and we can
848 // do simplifications that apply to *just* the one user if we know that
849 // this instruction has a simpler value in that context.
850 if (I->getOpcode() == Instruction::And) {
851 // If either the LHS or the RHS are Zero, the result is zero.
852 ComputeMaskedBits(I->getOperand(1), DemandedMask,
853 RHSKnownZero, RHSKnownOne, Depth+1);
854 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
855 LHSKnownZero, LHSKnownOne, Depth+1);
856
857 // If all of the demanded bits are known 1 on one side, return the other.
858 // These bits cannot contribute to the result of the 'and' in this
859 // context.
860 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
861 (DemandedMask & ~LHSKnownZero))
862 return I->getOperand(0);
863 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
864 (DemandedMask & ~RHSKnownZero))
865 return I->getOperand(1);
866
867 // If all of the demanded bits in the inputs are known zeros, return zero.
868 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000869 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000870
871 } else if (I->getOpcode() == Instruction::Or) {
872 // We can simplify (X|Y) -> X or Y in the user's context if we know that
873 // only bits from X or Y are demanded.
874
875 // If either the LHS or the RHS are One, the result is One.
876 ComputeMaskedBits(I->getOperand(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1);
878 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
879 LHSKnownZero, LHSKnownOne, Depth+1);
880
881 // If all of the demanded bits are known zero on one side, return the
882 // other. These bits cannot contribute to the result of the 'or' in this
883 // context.
884 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
885 (DemandedMask & ~LHSKnownOne))
886 return I->getOperand(0);
887 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
888 (DemandedMask & ~RHSKnownOne))
889 return I->getOperand(1);
890
891 // If all of the potentially set bits on one side are known to be set on
892 // the other side, just use the 'other' side.
893 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
894 (DemandedMask & (~RHSKnownZero)))
895 return I->getOperand(0);
896 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
897 (DemandedMask & (~LHSKnownZero)))
898 return I->getOperand(1);
899 }
900
Chris Lattner4598c942009-01-31 08:24:16 +0000901 // Compute the KnownZero/KnownOne bits to simplify things downstream.
902 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
903 return 0;
904 }
905
906 // If this is the root being simplified, allow it to have multiple uses,
907 // just set the DemandedMask to all bits so that we can try to simplify the
908 // operands. This allows visitTruncInst (for example) to simplify the
909 // operand of a trunc without duplicating all the logic below.
910 if (Depth == 0 && !V->hasOneUse())
911 DemandedMask = APInt::getAllOnesValue(BitWidth);
912
Reid Spencer8cb68342007-03-12 17:25:59 +0000913 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000914 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000915 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000916 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000917 case Instruction::And:
918 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000919 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
920 RHSKnownZero, RHSKnownOne, Depth+1) ||
921 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 return I;
924 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
925 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000926
927 // If all of the demanded bits are known 1 on one side, return the other.
928 // These bits cannot contribute to the result of the 'and'.
929 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
930 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
933 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000934 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000935
936 // If all of the demanded bits in the inputs are known zeros, return zero.
937 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000938 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000939
940 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000941 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000943
944 // Output known-1 bits are only known if set in both the LHS & RHS.
945 RHSKnownOne &= LHSKnownOne;
946 // Output known-0 are known to be clear if zero in either the LHS | RHS.
947 RHSKnownZero |= LHSKnownZero;
948 break;
949 case Instruction::Or:
950 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000951 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
952 RHSKnownZero, RHSKnownOne, Depth+1) ||
953 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I;
956 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
957 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000958
959 // If all of the demanded bits are known zero on one side, return the other.
960 // These bits cannot contribute to the result of the 'or'.
961 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
962 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
965 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // If all of the potentially set bits on one side are known to be set on
969 // the other side, just use the 'other' side.
970 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
971 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
974 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000976
977 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000978 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // Output known-0 bits are only known if clear in both the LHS & RHS.
982 RHSKnownZero &= LHSKnownZero;
983 // Output known-1 are known to be set if set in either the LHS | RHS.
984 RHSKnownOne |= LHSKnownOne;
985 break;
986 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
988 RHSKnownZero, RHSKnownOne, Depth+1) ||
989 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000990 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I;
992 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
993 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // If all of the demanded bits are known zero on one side, return the other.
996 // These bits cannot contribute to the result of the 'xor'.
997 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000998 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000999 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
1002 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1003 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1004 (RHSKnownOne & LHSKnownOne);
1005 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1006 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1007 (RHSKnownOne & LHSKnownZero);
1008
1009 // If all of the demanded bits are known to be zero on one side or the
1010 // other, turn this into an *inclusive* or.
1011 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1012 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1013 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001014 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 }
1018
1019 // If all of the demanded bits on one side are known, and all of the set
1020 // bits on that side are also known to be set on the other side, turn this
1021 // into an AND, as we know the bits will be cleared.
1022 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1023 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1024 // all known
1025 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001026 Constant *AndC = ConstantInt::get(*Context,
1027 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001029 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 }
1032 }
1033
1034 // If the RHS is a constant, see if we can simplify it.
1035 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001036 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001037 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001038
1039 RHSKnownZero = KnownZeroOut;
1040 RHSKnownOne = KnownOneOut;
1041 break;
1042 }
1043 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1045 RHSKnownZero, RHSKnownOne, Depth+1) ||
1046 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001047 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 return I;
1049 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1050 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001051
1052 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001053 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1054 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 // Only known if known in both the LHS and RHS.
1058 RHSKnownOne &= LHSKnownOne;
1059 RHSKnownZero &= LHSKnownZero;
1060 break;
1061 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001062 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001063 DemandedMask.zext(truncBf);
1064 RHSKnownZero.zext(truncBf);
1065 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001067 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 DemandedMask.trunc(BitWidth);
1070 RHSKnownZero.trunc(BitWidth);
1071 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001072 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001073 break;
1074 }
1075 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001076 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001077 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001078
1079 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1080 if (const VectorType *SrcVTy =
1081 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1082 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1083 // Don't touch a bitcast between vectors of different element counts.
1084 return false;
1085 } else
1086 // Don't touch a scalar-to-vector bitcast.
1087 return false;
1088 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1089 // Don't touch a vector-to-scalar bitcast.
1090 return false;
1091
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 return I;
1095 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001096 break;
1097 case Instruction::ZExt: {
1098 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001099 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001100
Zhou Shengd48653a2007-03-29 04:45:55 +00001101 DemandedMask.trunc(SrcBitWidth);
1102 RHSKnownZero.trunc(SrcBitWidth);
1103 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001105 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 DemandedMask.zext(BitWidth);
1108 RHSKnownZero.zext(BitWidth);
1109 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001112 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 break;
1114 }
1115 case Instruction::SExt: {
1116 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001117 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001118
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001120 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001121
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 // If any of the sign extended bits are demanded, we know that the sign
1124 // bit is demanded.
1125 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001126 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
Zhou Shengd48653a2007-03-29 04:45:55 +00001128 InputDemandedBits.trunc(SrcBitWidth);
1129 RHSKnownZero.trunc(SrcBitWidth);
1130 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 InputDemandedBits.zext(BitWidth);
1135 RHSKnownZero.zext(BitWidth);
1136 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
1139 // If the sign bit of the input is known set or clear, then we know the
1140 // top bits of the result.
1141
1142 // If the input sign bit is known zero, or if the NewBits are not demanded
1143 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1147 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 }
1151 break;
1152 }
1153 case Instruction::Add: {
1154 // Figure out what the input bits are. If the top bits of the and result
1155 // are not demanded, then the add doesn't demand them from its input
1156 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001158
1159 // If there is a constant on the RHS, there are a variety of xformations
1160 // we can do.
1161 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162 // If null, this should be simplified elsewhere. Some of the xforms here
1163 // won't work if the RHS is zero.
1164 if (RHS->isZero())
1165 break;
1166
1167 // If the top bit of the output is demanded, demand everything from the
1168 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001169 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
1176 // If the RHS of the add has bits set that can't affect the input, reduce
1177 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001178 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001179 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
1181 // Avoid excess work.
1182 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1183 break;
1184
1185 // Turn it into OR if input bits are zero.
1186 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1187 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001188 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 }
1192
1193 // We can say something about the output known-zero and known-one bits,
1194 // depending on potential carries from the input constant and the
1195 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1196 // bits set and the RHS constant is 0x01001, then we know we have a known
1197 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1198
1199 // To compute this, we first compute the potential carry bits. These are
1200 // the bits which may be modified. I'm not aware of a better way to do
1201 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001203 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001204
1205 // Now that we know which bits have carries, compute the known-1/0 sets.
1206
1207 // Bits are known one if they are known zero in one operand and one in the
1208 // other, and there is no input carry.
1209 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1210 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1211
1212 // Bits are known zero if they are known zero in both operands and there
1213 // is no input carry.
1214 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1215 } else {
1216 // If the high-bits of this ADD are not demanded, then it does not demand
1217 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 // Right fill the mask of bits for this ADD to demand the most
1220 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001221 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1223 LHSKnownZero, LHSKnownOne, Depth+1) ||
1224 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 }
1228 }
1229 break;
1230 }
1231 case Instruction::Sub:
1232 // If the high-bits of this SUB are not demanded, then it does not demand
1233 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 // Right fill the mask of bits for this SUB to demand the most
1236 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001237 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001238 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1240 LHSKnownZero, LHSKnownOne, Depth+1) ||
1241 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001245 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1246 // the known zeros and ones.
1247 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 break;
1249 case Instruction::Shl:
1250 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001251 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001252 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 return I;
1256 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 RHSKnownZero <<= ShiftAmt;
1258 RHSKnownOne <<= ShiftAmt;
1259 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001260 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001261 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 }
1263 break;
1264 case Instruction::LShr:
1265 // For a logical shift right
1266 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001267 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001270 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 return I;
1274 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1276 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001277 if (ShiftAmt) {
1278 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001279 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001280 RHSKnownZero |= HighBits; // high bits known zero.
1281 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 }
1283 break;
1284 case Instruction::AShr:
1285 // If this is an arithmetic shift right and only the low-bit is set, we can
1286 // always convert this into a logical shr, even if the shift amount is
1287 // variable. The low bit of the shift cannot be an input sign bit unless
1288 // the shift amount is >= the size of the datatype, which is undefined.
1289 if (DemandedMask == 1) {
1290 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001295
1296 // If the sign bit is the only bit demanded by this ashr, then there is no
1297 // need to do it, the shift doesn't change the high bit.
1298 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001299 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
1301 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001302 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001303
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001306 // If any of the "high bits" are demanded, we should set the sign bit as
1307 // demanded.
1308 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1309 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001312 return I;
1313 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001315 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1317 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1318
1319 // Handle the sign bits.
1320 APInt SignBit(APInt::getSignBit(BitWidth));
1321 // Adjust to where it is now in the mask.
1322 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1323
1324 // If the input sign bit is known to be zero, or if none of the top bits
1325 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001326 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 (HighBits & ~DemandedMask) == HighBits) {
1328 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1333 RHSKnownOne |= HighBits;
1334 }
1335 }
1336 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001337 case Instruction::SRem:
1338 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001339 APInt RA = Rem->getValue().abs();
1340 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001341 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001343
Nick Lewycky8e394322008-11-02 02:41:50 +00001344 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349
1350 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1351 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352
1353 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001354
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001356 }
1357 }
1358 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001359 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001360 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1361 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1363 KnownZero2, KnownOne2, Depth+1) ||
1364 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001365 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001366 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001367
Chris Lattner455e9ab2009-01-21 18:09:24 +00001368 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001369 Leaders = std::max(Leaders,
1370 KnownZero2.countLeadingOnes());
1371 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001373 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001374 case Instruction::Call:
1375 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1376 switch (II->getIntrinsicID()) {
1377 default: break;
1378 case Intrinsic::bswap: {
1379 // If the only bits demanded come from one byte of the bswap result,
1380 // just shift the input byte into position to eliminate the bswap.
1381 unsigned NLZ = DemandedMask.countLeadingZeros();
1382 unsigned NTZ = DemandedMask.countTrailingZeros();
1383
1384 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1385 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1386 // have 14 leading zeros, round to 8.
1387 NLZ &= ~7;
1388 NTZ &= ~7;
1389 // If we need exactly one byte, we can do this transformation.
1390 if (BitWidth-NLZ-NTZ == 8) {
1391 unsigned ResultBit = NTZ;
1392 unsigned InputBit = BitWidth-NTZ-8;
1393
1394 // Replace this with either a left or right shift to get the byte into
1395 // the right place.
1396 Instruction *NewVal;
1397 if (InputBit > ResultBit)
1398 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001399 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001400 else
1401 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001402 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001404 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001405 }
1406
1407 // TODO: Could compute known zero/one bits based on the input.
1408 break;
1409 }
1410 }
1411 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001412 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001413 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001414 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001415
1416 // If the client is only demanding bits that we know, return the known
1417 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001418 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001419 Constant *C = ConstantInt::get(*Context, RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001420 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001421 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001422 return C;
1423 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001424 return false;
1425}
1426
Chris Lattner867b99f2006-10-05 06:55:50 +00001427
Mon P Wangaeb06d22008-11-10 04:46:22 +00001428/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001429/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001430/// actually used by the caller. This method analyzes which elements of the
1431/// operand are undef and returns that information in UndefElts.
1432///
1433/// If the information about demanded elements can be used to simplify the
1434/// operation, the operation is simplified, then the resultant value is
1435/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001436Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1437 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001439 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001440 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001441 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001442
1443 if (isa<UndefValue>(V)) {
1444 // If the entire vector is undefined, just return this info.
1445 UndefElts = EltMask;
1446 return 0;
1447 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1448 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001449 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001451
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1454 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001455 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001456
1457 std::vector<Constant*> Elts;
1458 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001459 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001461 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1463 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001464 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 } else { // Otherwise, defined.
1466 Elts.push_back(CP->getOperand(i));
1467 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001468
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001470 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 return NewCP != CP ? NewCP : 0;
1472 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001473 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001474 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001475
1476 // Check if this is identity. If so, return 0 since we are not simplifying
1477 // anything.
1478 if (DemandedElts == ((1ULL << VWidth) -1))
1479 return 0;
1480
Reid Spencer9d6565a2007-02-15 02:26:10 +00001481 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001482 Constant *Zero = Context->getNullValue(EltTy);
1483 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001485 for (unsigned i = 0; i != VWidth; ++i) {
1486 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1487 Elts.push_back(Elt);
1488 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001489 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001490 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 }
1492
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493 // Limit search depth.
1494 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001495 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001496
1497 // If multiple users are using the root value, procede with
1498 // simplification conservatively assuming that all elements
1499 // are needed.
1500 if (!V->hasOneUse()) {
1501 // Quit if we find multiple users of a non-root value though.
1502 // They'll be handled when it's their turn to be visited by
1503 // the main instcombine process.
1504 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001506 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001507
1508 // Conservatively assume that all elements are needed.
1509 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 }
1511
1512 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001513 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001514
1515 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001516 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 Value *TmpV;
1518 switch (I->getOpcode()) {
1519 default: break;
1520
1521 case Instruction::InsertElement: {
1522 // If this is a variable index, we don't know which element it overwrites.
1523 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001524 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 if (Idx == 0) {
1526 // Note that we can't propagate undef elt info, because we don't know
1527 // which elt is getting updated.
1528 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1529 UndefElts2, Depth+1);
1530 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1531 break;
1532 }
1533
1534 // If this is inserting an element that isn't demanded, remove this
1535 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001536 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001537 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 return AddSoonDeadInstToWorklist(*I, 0);
1539
1540 // Otherwise, the element inserted overwrites whatever was there, so the
1541 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001542 APInt DemandedElts2 = DemandedElts;
1543 DemandedElts2.clear(IdxNo);
1544 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001545 UndefElts, Depth+1);
1546 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547
1548 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001549 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001550 break;
1551 }
1552 case Instruction::ShuffleVector: {
1553 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001554 uint64_t LHSVWidth =
1555 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001556 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001558 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001559 unsigned MaskVal = Shuffle->getMaskValue(i);
1560 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001561 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001563 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001564 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 else
Evan Cheng388df622009-02-03 10:05:09 +00001566 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 }
1568 }
1569 }
1570
Nate Begeman7b254672009-02-11 22:36:25 +00001571 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001573 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1575
Nate Begeman7b254672009-02-11 22:36:25 +00001576 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1578 UndefElts3, Depth+1);
1579 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1580
1581 bool NewUndefElts = false;
1582 for (unsigned i = 0; i < VWidth; i++) {
1583 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001584 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001585 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001586 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001587 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001588 NewUndefElts = true;
1589 UndefElts.set(i);
1590 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001592 if (UndefElts3[MaskVal - LHSVWidth]) {
1593 NewUndefElts = true;
1594 UndefElts.set(i);
1595 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001596 }
1597 }
1598
1599 if (NewUndefElts) {
1600 // Add additional discovered undefs.
1601 std::vector<Constant*> Elts;
1602 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001603 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001604 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 else
Owen Andersoneed707b2009-07-24 23:12:02 +00001606 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001607 Shuffle->getMaskValue(i)));
1608 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001609 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 MadeChange = true;
1611 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001612 break;
1613 }
Chris Lattner69878332007-04-14 22:29:23 +00001614 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001615 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001616 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1617 if (!VTy) break;
1618 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001619 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001620 unsigned Ratio;
1621
1622 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001623 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001624 // elements as are demanded of us.
1625 Ratio = 1;
1626 InputDemandedElts = DemandedElts;
1627 } else if (VWidth > InVWidth) {
1628 // Untested so far.
1629 break;
1630
1631 // If there are more elements in the result than there are in the source,
1632 // then an input element is live if any of the corresponding output
1633 // elements are live.
1634 Ratio = VWidth/InVWidth;
1635 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001636 if (DemandedElts[OutIdx])
1637 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001638 }
1639 } else {
1640 // Untested so far.
1641 break;
1642
1643 // If there are more elements in the source than there are in the result,
1644 // then an input element is live if the corresponding output element is
1645 // live.
1646 Ratio = InVWidth/VWidth;
1647 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001648 if (DemandedElts[InIdx/Ratio])
1649 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001650 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001651
Chris Lattner69878332007-04-14 22:29:23 +00001652 // div/rem demand all inputs, because they don't want divide by zero.
1653 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1654 UndefElts2, Depth+1);
1655 if (TmpV) {
1656 I->setOperand(0, TmpV);
1657 MadeChange = true;
1658 }
1659
1660 UndefElts = UndefElts2;
1661 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001662 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001663 // If there are more elements in the result than there are in the source,
1664 // then an output element is undef if the corresponding input element is
1665 // undef.
1666 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001667 if (UndefElts2[OutIdx/Ratio])
1668 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001669 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001670 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001671 // If there are more elements in the source than there are in the result,
1672 // then a result element is undef if all of the corresponding input
1673 // elements are undef.
1674 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1675 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001676 if (!UndefElts2[InIdx]) // Not undef?
1677 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001678 }
1679 break;
1680 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001681 case Instruction::And:
1682 case Instruction::Or:
1683 case Instruction::Xor:
1684 case Instruction::Add:
1685 case Instruction::Sub:
1686 case Instruction::Mul:
1687 // div/rem demand all inputs, because they don't want divide by zero.
1688 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1689 UndefElts, Depth+1);
1690 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1691 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1692 UndefElts2, Depth+1);
1693 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1694
1695 // Output elements are undefined if both are undefined. Consider things
1696 // like undef&0. The result is known zero, not undef.
1697 UndefElts &= UndefElts2;
1698 break;
1699
1700 case Instruction::Call: {
1701 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1702 if (!II) break;
1703 switch (II->getIntrinsicID()) {
1704 default: break;
1705
1706 // Binary vector operations that work column-wise. A dest element is a
1707 // function of the corresponding input elements from the two inputs.
1708 case Intrinsic::x86_sse_sub_ss:
1709 case Intrinsic::x86_sse_mul_ss:
1710 case Intrinsic::x86_sse_min_ss:
1711 case Intrinsic::x86_sse_max_ss:
1712 case Intrinsic::x86_sse2_sub_sd:
1713 case Intrinsic::x86_sse2_mul_sd:
1714 case Intrinsic::x86_sse2_min_sd:
1715 case Intrinsic::x86_sse2_max_sd:
1716 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1717 UndefElts, Depth+1);
1718 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1719 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1720 UndefElts2, Depth+1);
1721 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1722
1723 // If only the low elt is demanded and this is a scalarizable intrinsic,
1724 // scalarize it now.
1725 if (DemandedElts == 1) {
1726 switch (II->getIntrinsicID()) {
1727 default: break;
1728 case Intrinsic::x86_sse_sub_ss:
1729 case Intrinsic::x86_sse_mul_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
1731 case Intrinsic::x86_sse2_mul_sd:
1732 // TODO: Lower MIN/MAX/ABS/etc
1733 Value *LHS = II->getOperand(1);
1734 Value *RHS = II->getOperand(2);
1735 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001736 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001737 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001738 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001739 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001740
1741 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001742 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001743 case Intrinsic::x86_sse_sub_ss:
1744 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001745 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001746 II->getName()), *II);
1747 break;
1748 case Intrinsic::x86_sse_mul_ss:
1749 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001750 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001751 II->getName()), *II);
1752 break;
1753 }
1754
1755 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001756 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001757 Context->getUndef(II->getType()), TmpV,
Owen Andersoneed707b2009-07-24 23:12:02 +00001758 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 InsertNewInstBefore(New, *II);
1760 AddSoonDeadInstToWorklist(*II, 0);
1761 return New;
1762 }
1763 }
1764
1765 // Output elements are undefined if both are undefined. Consider things
1766 // like undef&0. The result is known zero, not undef.
1767 UndefElts &= UndefElts2;
1768 break;
1769 }
1770 break;
1771 }
1772 }
1773 return MadeChange ? I : 0;
1774}
1775
Dan Gohman45b4e482008-05-19 22:14:15 +00001776
Chris Lattner564a7272003-08-13 19:01:45 +00001777/// AssociativeOpt - Perform an optimization on an associative operator. This
1778/// function is designed to check a chain of associative operators for a
1779/// potential to apply a certain optimization. Since the optimization may be
1780/// applicable if the expression was reassociated, this checks the chain, then
1781/// reassociates the expression as necessary to expose the optimization
1782/// opportunity. This makes use of a special Functor, which must define
1783/// 'shouldApply' and 'apply' methods.
1784///
1785template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001786static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001787 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001788 unsigned Opcode = Root.getOpcode();
1789 Value *LHS = Root.getOperand(0);
1790
1791 // Quick check, see if the immediate LHS matches...
1792 if (F.shouldApply(LHS))
1793 return F.apply(Root);
1794
1795 // Otherwise, if the LHS is not of the same opcode as the root, return.
1796 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001797 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001798 // Should we apply this transform to the RHS?
1799 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1800
1801 // If not to the RHS, check to see if we should apply to the LHS...
1802 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1803 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1804 ShouldApply = true;
1805 }
1806
1807 // If the functor wants to apply the optimization to the RHS of LHSI,
1808 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1809 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001810 // Now all of the instructions are in the current basic block, go ahead
1811 // and perform the reassociation.
1812 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1813
1814 // First move the selected RHS to the LHS of the root...
1815 Root.setOperand(0, LHSI->getOperand(1));
1816
1817 // Make what used to be the LHS of the root be the user of the root...
1818 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001819 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001820 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001821 return 0;
1822 }
Chris Lattner65725312004-04-16 18:08:07 +00001823 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001824 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001825 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001826 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001827 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001828
1829 // Now propagate the ExtraOperand down the chain of instructions until we
1830 // get to LHSI.
1831 while (TmpLHSI != LHSI) {
1832 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001833 // Move the instruction to immediately before the chain we are
1834 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001835 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001836 ARI = NextLHSI;
1837
Chris Lattner564a7272003-08-13 19:01:45 +00001838 Value *NextOp = NextLHSI->getOperand(1);
1839 NextLHSI->setOperand(1, ExtraOperand);
1840 TmpLHSI = NextLHSI;
1841 ExtraOperand = NextOp;
1842 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001843
Chris Lattner564a7272003-08-13 19:01:45 +00001844 // Now that the instructions are reassociated, have the functor perform
1845 // the transformation...
1846 return F.apply(Root);
1847 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001848
Chris Lattner564a7272003-08-13 19:01:45 +00001849 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1850 }
1851 return 0;
1852}
1853
Dan Gohman844731a2008-05-13 00:00:25 +00001854namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001855
Nick Lewycky02d639f2008-05-23 04:34:58 +00001856// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001857struct AddRHS {
1858 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001859 LLVMContext *Context;
1860 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001861 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1862 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001863 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001864 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001865 }
1866};
1867
1868// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1869// iff C1&C2 == 0
1870struct AddMaskingAnd {
1871 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001872 LLVMContext *Context;
1873 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001874 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001875 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001876 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001877 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001880 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001881 }
1882};
1883
Dan Gohman844731a2008-05-13 00:00:25 +00001884}
1885
Chris Lattner6e7ba452005-01-01 16:22:27 +00001886static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001887 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001888 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001889
Reid Spencer3da59db2006-11-27 01:05:10 +00001890 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001891 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892 }
1893
Chris Lattner2eefe512004-04-09 19:05:30 +00001894 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001895 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1896 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001897
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1899 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001900 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1901 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001902 }
1903
1904 Value *Op0 = SO, *Op1 = ConstOperand;
1905 if (!ConstIsRHS)
1906 std::swap(Op0, Op1);
1907 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001909 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001910 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001911 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1912 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001913 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001914 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001915 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001916 return IC->InsertNewInstBefore(New, I);
1917}
1918
1919// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1920// constant as the other operand, try to fold the binary operator into the
1921// select arguments. This also works for Cast instructions, which obviously do
1922// not have a second operand.
1923static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1924 InstCombiner *IC) {
1925 // Don't modify shared select instructions
1926 if (!SI->hasOneUse()) return 0;
1927 Value *TV = SI->getOperand(1);
1928 Value *FV = SI->getOperand(2);
1929
1930 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001931 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001932 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001933
Chris Lattner6e7ba452005-01-01 16:22:27 +00001934 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1935 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1936
Gabor Greif051a9502008-04-06 20:25:17 +00001937 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1938 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001939 }
1940 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001941}
1942
Chris Lattner4e998b22004-09-29 05:07:12 +00001943
1944/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1945/// node as operand #0, see if we can fold the instruction into the PHI (which
1946/// is only possible if all operands to the PHI are constants).
1947Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1948 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001949 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001950 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001951
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001952 // Check to see if all of the operands of the PHI are constants. If there is
1953 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001954 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001955 BasicBlock *NonConstBB = 0;
1956 for (unsigned i = 0; i != NumPHIValues; ++i)
1957 if (!isa<Constant>(PN->getIncomingValue(i))) {
1958 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001959 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001960 NonConstBB = PN->getIncomingBlock(i);
1961
1962 // If the incoming non-constant value is in I's block, we have an infinite
1963 // loop.
1964 if (NonConstBB == I.getParent())
1965 return 0;
1966 }
1967
1968 // If there is exactly one non-constant value, we can insert a copy of the
1969 // operation in that block. However, if this is a critical edge, we would be
1970 // inserting the computation one some other paths (e.g. inside a loop). Only
1971 // do this if the pred block is unconditionally branching into the phi block.
1972 if (NonConstBB) {
1973 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1974 if (!BI || !BI->isUnconditional()) return 0;
1975 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001976
1977 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001978 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001979 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001980 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001981 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001982
1983 // Next, add all of the operands to the PHI.
1984 if (I.getNumOperands() == 2) {
1985 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001986 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001987 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001988 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001989 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001990 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001991 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001992 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 } else {
1994 assert(PN->getIncomingBlock(i) == NonConstBB);
1995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001996 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 PN->getIncomingValue(i), C, "phitmp",
1998 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001999 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002000 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002001 CI->getPredicate(),
2002 PN->getIncomingValue(i), C, "phitmp",
2003 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002005 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006
Chris Lattnerdbab3862007-03-02 21:28:56 +00002007 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 }
2009 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002010 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002011 } else {
2012 CastInst *CI = cast<CastInst>(&I);
2013 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002014 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 Value *InV;
2016 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002017 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002018 } else {
2019 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002020 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002021 I.getType(), "phitmp",
2022 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002023 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 }
2025 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002026 }
2027 }
2028 return ReplaceInstUsesWith(I, NewPN);
2029}
2030
Chris Lattner2454a2e2008-01-29 06:52:45 +00002031
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002032/// WillNotOverflowSignedAdd - Return true if we can prove that:
2033/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2034/// This basically requires proving that the add in the original type would not
2035/// overflow to change the sign bit or have a carry out.
2036bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2037 // There are different heuristics we can use for this. Here are some simple
2038 // ones.
2039
2040 // Add has the property that adding any two 2's complement numbers can only
2041 // have one carry bit which can change a sign. As such, if LHS and RHS each
2042 // have at least two sign bits, we know that the addition of the two values will
2043 // sign extend fine.
2044 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2045 return true;
2046
2047
2048 // If one of the operands only has one non-zero bit, and if the other operand
2049 // has a known-zero bit in a more significant place than it (not including the
2050 // sign bit) the ripple may go up to and fill the zero, but won't change the
2051 // sign. For example, (X & ~4) + 1.
2052
2053 // TODO: Implement.
2054
2055 return false;
2056}
2057
Chris Lattner2454a2e2008-01-29 06:52:45 +00002058
Chris Lattner7e708292002-06-25 16:13:24 +00002059Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002060 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002061 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002062
Chris Lattner66331a42004-04-10 22:01:55 +00002063 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002064 // X + undef -> undef
2065 if (isa<UndefValue>(RHS))
2066 return ReplaceInstUsesWith(I, RHS);
2067
Chris Lattner66331a42004-04-10 22:01:55 +00002068 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002069 if (RHSC->isNullValue())
2070 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002071
Chris Lattner66331a42004-04-10 22:01:55 +00002072 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002073 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002074 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002075 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002076 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002077 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002078
2079 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2080 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002081 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002082 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002083
Eli Friedman709b33d2009-07-13 22:27:52 +00002084 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002085 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002086 if (ZI->getSrcTy() == Type::Int1Ty)
2087 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002088 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002089
2090 if (isa<PHINode>(LHS))
2091 if (Instruction *NV = FoldOpIntoPhi(I))
2092 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002093
Chris Lattner4f637d42006-01-06 17:59:59 +00002094 ConstantInt *XorRHS = 0;
2095 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002096 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002097 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002098 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002099 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002100
Zhou Sheng4351c642007-04-02 08:20:41 +00002101 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002102 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2103 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002104 do {
2105 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002106 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2107 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002108 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2109 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002110 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002111 if (!MaskedValueIsZero(XorLHS,
2112 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002113 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002114 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002115 }
2116 }
2117 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002118 C0080Val = APIntOps::lshr(C0080Val, Size);
2119 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2120 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002121
Reid Spencer35c38852007-03-28 01:36:16 +00002122 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002123 // with funny bit widths then this switch statement should be removed. It
2124 // is just here to get the size of the "middle" type back up to something
2125 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002126 const Type *MiddleType = 0;
2127 switch (Size) {
2128 default: break;
2129 case 32: MiddleType = Type::Int32Ty; break;
2130 case 16: MiddleType = Type::Int16Ty; break;
2131 case 8: MiddleType = Type::Int8Ty; break;
2132 }
2133 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002134 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002135 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002136 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002137 }
2138 }
Chris Lattner66331a42004-04-10 22:01:55 +00002139 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002140
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002141 if (I.getType() == Type::Int1Ty)
2142 return BinaryOperator::CreateXor(LHS, RHS);
2143
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002144 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002145 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002146 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2147 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002148
2149 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2150 if (RHSI->getOpcode() == Instruction::Sub)
2151 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2152 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2153 }
2154 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2155 if (LHSI->getOpcode() == Instruction::Sub)
2156 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2157 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2158 }
Robert Bocchino71698282004-07-27 21:02:21 +00002159 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002160
Chris Lattner5c4afb92002-05-08 22:46:53 +00002161 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002162 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002163 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002164 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002165 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002166 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002167 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002168 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002169 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002170 }
2171
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002172 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002173 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002174
2175 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002176 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002177 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002178 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002179
Misha Brukmanfd939082005-04-21 23:48:37 +00002180
Chris Lattner50af16a2004-11-13 19:50:12 +00002181 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002182 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002183 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002184 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002185
2186 // X*C1 + X*C2 --> X * (C1+C2)
2187 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002188 if (X == dyn_castFoldableMul(RHS, C1, Context))
2189 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002190 }
2191
2192 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002193 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2194 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002195
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002197 if (dyn_castNotVal(LHS, Context) == RHS ||
2198 dyn_castNotVal(RHS, Context) == LHS)
2199 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002200
Chris Lattnerad3448c2003-02-18 19:57:07 +00002201
Chris Lattner564a7272003-08-13 19:01:45 +00002202 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002203 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002204 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002205 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002206
2207 // A+B --> A|B iff A and B have no bits set in common.
2208 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2209 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2210 APInt LHSKnownOne(IT->getBitWidth(), 0);
2211 APInt LHSKnownZero(IT->getBitWidth(), 0);
2212 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2213 if (LHSKnownZero != 0) {
2214 APInt RHSKnownOne(IT->getBitWidth(), 0);
2215 APInt RHSKnownZero(IT->getBitWidth(), 0);
2216 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2217
2218 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002219 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002220 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002221 }
2222 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002223
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002224 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002225 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002226 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002227 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2228 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002229 if (W != Y) {
2230 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002231 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002232 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002233 std::swap(W, X);
2234 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002235 std::swap(Y, Z);
2236 std::swap(W, X);
2237 }
2238 }
2239
2240 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002241 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002243 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002244 }
2245 }
2246 }
2247
Chris Lattner6b032052003-10-02 15:11:26 +00002248 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002249 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002250 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002251 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002252
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002253 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002254 if (LHS->hasOneUse() &&
2255 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002256 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002257 if (Anded == CRHS) {
2258 // See if all bits from the first bit set in the Add RHS up are included
2259 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002260 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002261
2262 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002263 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264
2265 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002266 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002267
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002268 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2269 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002270 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002271 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002272 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273 }
2274 }
2275 }
2276
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002277 // Try to fold constant add into select arguments.
2278 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002279 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002280 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002281 }
2282
Chris Lattner42790482007-12-20 01:56:58 +00002283 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002284 {
2285 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002286 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002287 if (!SI) {
2288 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002290 }
Chris Lattner42790482007-12-20 01:56:58 +00002291 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002292 Value *TV = SI->getTrueValue();
2293 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002294 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295
2296 // Can we fold the add into the argument of the select?
2297 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002298 if (match(FV, m_Zero(), *Context) &&
2299 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002301 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002302 if (match(TV, m_Zero(), *Context) &&
2303 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002304 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002305 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002306 }
2307 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002309 // Check for (add (sext x), y), see if we can merge this into an
2310 // integer add followed by a sext.
2311 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2312 // (add (sext x), cst) --> (sext (add x, cst'))
2313 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2314 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002315 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002316 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002317 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002318 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2319 // Insert the new, smaller add.
2320 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2321 CI, "addconv");
2322 InsertNewInstBefore(NewAdd, I);
2323 return new SExtInst(NewAdd, I.getType());
2324 }
2325 }
2326
2327 // (add (sext x), (sext y)) --> (sext (add int x, y))
2328 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2329 // Only do this if x/y have the same type, if at last one of them has a
2330 // single use (so we don't increase the number of sexts), and if the
2331 // integer add will not overflow.
2332 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2333 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2334 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2335 RHSConv->getOperand(0))) {
2336 // Insert the new integer add.
2337 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2338 RHSConv->getOperand(0),
2339 "addconv");
2340 InsertNewInstBefore(NewAdd, I);
2341 return new SExtInst(NewAdd, I.getType());
2342 }
2343 }
2344 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002345
2346 return Changed ? &I : 0;
2347}
2348
2349Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2350 bool Changed = SimplifyCommutative(I);
2351 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2352
2353 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2354 // X + 0 --> X
2355 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002356 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002357 (I.getType())->getValueAPF()))
2358 return ReplaceInstUsesWith(I, LHS);
2359 }
2360
2361 if (isa<PHINode>(LHS))
2362 if (Instruction *NV = FoldOpIntoPhi(I))
2363 return NV;
2364 }
2365
2366 // -A + B --> B - A
2367 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002368 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002369 return BinaryOperator::CreateFSub(RHS, LHSV);
2370
2371 // A + -B --> A - B
2372 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002373 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002374 return BinaryOperator::CreateFSub(LHS, V);
2375
2376 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2377 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2378 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2379 return ReplaceInstUsesWith(I, LHS);
2380
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002381 // Check for (add double (sitofp x), y), see if we can merge this into an
2382 // integer add followed by a promotion.
2383 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2384 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2385 // ... if the constant fits in the integer value. This is useful for things
2386 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2387 // requires a constant pool load, and generally allows the add to be better
2388 // instcombined.
2389 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2390 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002391 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002392 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002393 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002394 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2395 // Insert the new integer add.
2396 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2397 CI, "addconv");
2398 InsertNewInstBefore(NewAdd, I);
2399 return new SIToFPInst(NewAdd, I.getType());
2400 }
2401 }
2402
2403 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2404 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2405 // Only do this if x/y have the same type, if at last one of them has a
2406 // single use (so we don't increase the number of int->fp conversions),
2407 // and if the integer add will not overflow.
2408 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2409 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2410 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2411 RHSConv->getOperand(0))) {
2412 // Insert the new integer add.
2413 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2414 RHSConv->getOperand(0),
2415 "addconv");
2416 InsertNewInstBefore(NewAdd, I);
2417 return new SIToFPInst(NewAdd, I.getType());
2418 }
2419 }
2420 }
2421
Chris Lattner7e708292002-06-25 16:13:24 +00002422 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002423}
2424
Chris Lattner7e708292002-06-25 16:13:24 +00002425Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002427
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002428 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002429 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002430
Chris Lattner233f7dc2002-08-12 21:17:25 +00002431 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002432 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002434
Chris Lattnere87597f2004-10-16 18:11:37 +00002435 if (isa<UndefValue>(Op0))
2436 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2437 if (isa<UndefValue>(Op1))
2438 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2439
Chris Lattnerd65460f2003-11-05 01:06:05 +00002440 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2441 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002442 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002443 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002444
Chris Lattnerd65460f2003-11-05 01:06:05 +00002445 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002446 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002447 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002448 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002449
Chris Lattner76b7a062007-01-15 07:02:54 +00002450 // -(X >>u 31) -> (X >>s 31)
2451 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002452 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002453 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002454 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002455 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002456 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002457 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002458 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002459 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002460 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002461 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002462 }
2463 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002464 }
2465 else if (SI->getOpcode() == Instruction::AShr) {
2466 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2467 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002468 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002469 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002470 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002472 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002473 }
2474 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002475 }
2476 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002477 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002478
2479 // Try to fold constant sub into select arguments.
2480 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002482 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002483
2484 // C - zext(bool) -> bool ? C - 1 : C
2485 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2486 if (ZI->getSrcTy() == Type::Int1Ty)
2487 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002488 }
2489
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002490 if (I.getType() == Type::Int1Ty)
2491 return BinaryOperator::CreateXor(Op0, Op1);
2492
Chris Lattner43d84d62005-04-07 16:15:25 +00002493 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002494 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002495 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002496 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2497 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002498 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002499 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2500 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002501 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2502 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2503 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002504 return BinaryOperator::CreateSub(
2505 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002506 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002507 }
2508
Chris Lattnerfd059242003-10-15 16:48:29 +00002509 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002510 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2511 // is not used by anyone else...
2512 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002513 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002514 // Swap the two operands of the subexpr...
2515 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2516 Op1I->setOperand(0, IIOp1);
2517 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002518
Chris Lattnera2881962003-02-18 19:28:33 +00002519 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002521 }
2522
2523 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2524 //
2525 if (Op1I->getOpcode() == Instruction::And &&
2526 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2527 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2528
Chris Lattnerf523d062004-06-09 05:08:07 +00002529 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002530 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2531 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002533 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002534
Reid Spencerac5209e2006-10-16 23:08:08 +00002535 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002536 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002537 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002538 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002539 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002540 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002541 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002542
Chris Lattnerad3448c2003-02-18 19:57:07 +00002543 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002544 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002545 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2546 Constant *CP1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00002547 Context->getConstantExprSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002548 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002549 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002550 }
Chris Lattner40371712002-05-09 01:29:19 +00002551 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002552 }
Chris Lattnera2881962003-02-18 19:28:33 +00002553
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002554 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2555 if (Op0I->getOpcode() == Instruction::Add) {
2556 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2557 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2558 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2559 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2560 } else if (Op0I->getOpcode() == Instruction::Sub) {
2561 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002562 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2563 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002564 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002565 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002566
Chris Lattner50af16a2004-11-13 19:50:12 +00002567 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002568 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002569 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002570 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002571
Chris Lattner50af16a2004-11-13 19:50:12 +00002572 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002573 if (X == dyn_castFoldableMul(Op1, C2, Context))
2574 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002575 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002576 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002577}
2578
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002579Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2581
2582 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002583 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002584 return BinaryOperator::CreateFAdd(Op0, V);
2585
2586 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2587 if (Op1I->getOpcode() == Instruction::FAdd) {
2588 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002589 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2590 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002592 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2593 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002595 }
2596
2597 return 0;
2598}
2599
Chris Lattnera0141b92007-07-15 20:42:37 +00002600/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2601/// comparison only checks the sign bit. If it only checks the sign bit, set
2602/// TrueIfSigned if the result of the comparison is true when the input value is
2603/// signed.
2604static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2605 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002606 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002607 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2608 TrueIfSigned = true;
2609 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002610 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2611 TrueIfSigned = true;
2612 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002613 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2614 TrueIfSigned = false;
2615 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002616 case ICmpInst::ICMP_UGT:
2617 // True if LHS u> RHS and RHS == high-bit-mask - 1
2618 TrueIfSigned = true;
2619 return RHS->getValue() ==
2620 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2621 case ICmpInst::ICMP_UGE:
2622 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2623 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002624 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002625 default:
2626 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002627 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002628}
2629
Chris Lattner7e708292002-06-25 16:13:24 +00002630Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002631 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002632 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002633
Eli Friedman1694e092009-07-18 09:12:15 +00002634 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002635 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002636
Chris Lattner233f7dc2002-08-12 21:17:25 +00002637 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002638 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2639 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002640
2641 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002642 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002643 if (SI->getOpcode() == Instruction::Shl)
2644 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002645 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002646 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002647
Zhou Sheng843f07672007-04-19 05:39:12 +00002648 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002649 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2650 if (CI->equalsInt(1)) // X * 1 == X
2651 return ReplaceInstUsesWith(I, Op0);
2652 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002653 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002654
Zhou Sheng97b52c22007-03-29 01:57:21 +00002655 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002656 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002657 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002658 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002659 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002660 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002661 if (Op1->isNullValue())
2662 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002663
2664 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2665 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002666 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002667
2668 // As above, vector X*splat(1.0) -> X in all defined cases.
2669 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002670 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2671 if (CI->equalsInt(1))
2672 return ReplaceInstUsesWith(I, Op0);
2673 }
2674 }
Chris Lattnera2881962003-02-18 19:28:33 +00002675 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002676
2677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2678 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002679 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002680 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002682 Op1, "tmp");
2683 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002684 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002685 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002687
2688 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002689
2690 // Try to fold constant mul into select arguments.
2691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002693 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002694
2695 if (isa<PHINode>(Op0))
2696 if (Instruction *NV = FoldOpIntoPhi(I))
2697 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002698 }
2699
Owen Andersond672ecb2009-07-03 00:17:18 +00002700 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2701 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002702 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002703
Nick Lewycky0c730792008-11-21 07:33:58 +00002704 // (X / Y) * Y = X - (X % Y)
2705 // (X / Y) * -Y = (X % Y) - X
2706 {
2707 Value *Op1 = I.getOperand(1);
2708 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2709 if (!BO ||
2710 (BO->getOpcode() != Instruction::UDiv &&
2711 BO->getOpcode() != Instruction::SDiv)) {
2712 Op1 = Op0;
2713 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2714 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002715 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002716 if (BO && BO->hasOneUse() &&
2717 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2718 (BO->getOpcode() == Instruction::UDiv ||
2719 BO->getOpcode() == Instruction::SDiv)) {
2720 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2721
2722 Instruction *Rem;
2723 if (BO->getOpcode() == Instruction::UDiv)
2724 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2725 else
2726 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2727
2728 InsertNewInstBefore(Rem, I);
2729 Rem->takeName(BO);
2730
2731 if (Op1BO == Op1)
2732 return BinaryOperator::CreateSub(Op0BO, Rem);
2733 else
2734 return BinaryOperator::CreateSub(Rem, Op0BO);
2735 }
2736 }
2737
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002738 if (I.getType() == Type::Int1Ty)
2739 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2740
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002741 // If one of the operands of the multiply is a cast from a boolean value, then
2742 // we know the bool is either zero or one, so this is a 'masking' multiply.
2743 // See if we can simplify things based on how the boolean was originally
2744 // formed.
2745 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 BoolCast = CI;
2749 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002750 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002751 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 BoolCast = CI;
2753 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002755 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002757 bool TIS = false;
2758
Reid Spencere4d87aa2006-12-23 06:05:41 +00002759 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002760 // multiply into a shift/and combination.
2761 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002762 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2763 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002764 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002765 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002766 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002767 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002768 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002770 BoolCast->getOperand(0)->getName()+
2771 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002772
2773 // If the multiply type is not the same as the source type, sign extend
2774 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002775 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002776 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2777 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002778 Instruction::CastOps opcode =
2779 (SrcBits == DstBits ? Instruction::BitCast :
2780 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2781 V = InsertCastBefore(opcode, V, I.getType(), I);
2782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002783
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002786 }
2787 }
2788 }
2789
Chris Lattner7e708292002-06-25 16:13:24 +00002790 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002791}
2792
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002793Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2794 bool Changed = SimplifyCommutative(I);
2795 Value *Op0 = I.getOperand(0);
2796
2797 // Simplify mul instructions with a constant RHS...
2798 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2799 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2800 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2801 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2802 if (Op1F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2804 } else if (isa<VectorType>(Op1->getType())) {
2805 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2806 // As above, vector X*splat(1.0) -> X in all defined cases.
2807 if (Constant *Splat = Op1V->getSplatValue()) {
2808 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2809 if (F->isExactlyValue(1.0))
2810 return ReplaceInstUsesWith(I, Op0);
2811 }
2812 }
2813 }
2814
2815 // Try to fold constant mul into select arguments.
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818 return R;
2819
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2822 return NV;
2823 }
2824
Owen Andersond672ecb2009-07-03 00:17:18 +00002825 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2826 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002827 return BinaryOperator::CreateFMul(Op0v, Op1v);
2828
2829 return Changed ? &I : 0;
2830}
2831
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002832/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2833/// instruction.
2834bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2835 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2836
2837 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2838 int NonNullOperand = -1;
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2840 if (ST->isNullValue())
2841 NonNullOperand = 2;
2842 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2843 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2844 if (ST->isNullValue())
2845 NonNullOperand = 1;
2846
2847 if (NonNullOperand == -1)
2848 return false;
2849
2850 Value *SelectCond = SI->getOperand(0);
2851
2852 // Change the div/rem to use 'Y' instead of the select.
2853 I.setOperand(1, SI->getOperand(NonNullOperand));
2854
2855 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2856 // problem. However, the select, or the condition of the select may have
2857 // multiple uses. Based on our knowledge that the operand must be non-zero,
2858 // propagate the known value for the select into other uses of it, and
2859 // propagate a known value of the condition into its other users.
2860
2861 // If the select and condition only have a single use, don't bother with this,
2862 // early exit.
2863 if (SI->use_empty() && SelectCond->hasOneUse())
2864 return true;
2865
2866 // Scan the current block backward, looking for other uses of SI.
2867 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2868
2869 while (BBI != BBFront) {
2870 --BBI;
2871 // If we found a call to a function, we can't assume it will return, so
2872 // information from below it cannot be propagated above it.
2873 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874 break;
2875
2876 // Replace uses of the select or its condition with the known values.
2877 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878 I != E; ++I) {
2879 if (*I == SI) {
2880 *I = SI->getOperand(NonNullOperand);
2881 AddToWorkList(BBI);
2882 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002883 *I = NonNullOperand == 1 ? Context->getTrue() :
2884 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002885 AddToWorkList(BBI);
2886 }
2887 }
2888
2889 // If we past the instruction, quit looking for it.
2890 if (&*BBI == SI)
2891 SI = 0;
2892 if (&*BBI == SelectCond)
2893 SelectCond = 0;
2894
2895 // If we ran out of things to eliminate, break out of the loop.
2896 if (SelectCond == 0 && SI == 0)
2897 break;
2898
2899 }
2900 return true;
2901}
2902
2903
Reid Spencer1628cec2006-10-26 06:15:43 +00002904/// This function implements the transforms on div instructions that work
2905/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2906/// used by the visitors to those instructions.
2907/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002908Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002909 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002910
Chris Lattner50b2ca42008-02-19 06:12:18 +00002911 // undef / X -> 0 for integer.
2912 // undef / X -> undef for FP (the undef could be a snan).
2913 if (isa<UndefValue>(Op0)) {
2914 if (Op0->getType()->isFPOrFPVector())
2915 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002916 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002917 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002918
2919 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002920 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002921 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002922
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 return 0;
2924}
Misha Brukmanfd939082005-04-21 23:48:37 +00002925
Reid Spencer1628cec2006-10-26 06:15:43 +00002926/// This function implements the transforms common to both integer division
2927/// instructions (udiv and sdiv). It is called by the visitors to those integer
2928/// division instructions.
2929/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002930Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002933 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002934 if (Op0 == Op1) {
2935 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002936 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002937 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002938 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002939 }
2940
Owen Andersoneed707b2009-07-24 23:12:02 +00002941 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002942 return ReplaceInstUsesWith(I, CI);
2943 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002944
Reid Spencer1628cec2006-10-26 06:15:43 +00002945 if (Instruction *Common = commonDivTransforms(I))
2946 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002947
2948 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2949 // This does not apply for fdiv.
2950 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002952
2953 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2954 // div X, 1 == X
2955 if (RHS->equalsInt(1))
2956 return ReplaceInstUsesWith(I, Op0);
2957
2958 // (X / C1) / C2 -> X / (C1*C2)
2959 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2960 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2961 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002962 if (MultiplyOverflows(RHS, LHSRHS,
2963 I.getOpcode()==Instruction::SDiv, Context))
2964 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002965 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002966 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002967 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002968 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002969
Reid Spencerbca0e382007-03-23 20:05:17 +00002970 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002971 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2972 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2973 return R;
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
2977 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002978 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002979
Chris Lattnera2881962003-02-18 19:28:33 +00002980 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002981 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002982 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00002983 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002984
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002985 // It can't be division by zero, hence it must be division by one.
2986 if (I.getType() == Type::Int1Ty)
2987 return ReplaceInstUsesWith(I, Op0);
2988
Nick Lewycky895f0852008-11-27 20:21:08 +00002989 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2990 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2991 // div X, 1 == X
2992 if (X->isOne())
2993 return ReplaceInstUsesWith(I, Op0);
2994 }
2995
Reid Spencer1628cec2006-10-26 06:15:43 +00002996 return 0;
2997}
2998
2999Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3001
3002 // Handle the integer div common cases
3003 if (Instruction *Common = commonIDivTransforms(I))
3004 return Common;
3005
Reid Spencer1628cec2006-10-26 06:15:43 +00003006 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003007 // X udiv C^2 -> X >> C
3008 // Check to see if this is an unsigned division with an exact power of 2,
3009 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003010 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003011 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003012 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003013
3014 // X udiv C, where C >= signbit
3015 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003016 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3017 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003018 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003019 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003020 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003021 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 }
3023
3024 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003025 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 if (RHSI->getOpcode() == Instruction::Shl &&
3027 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003028 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003029 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003030 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003031 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003032 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003033 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003035 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003036 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003037 }
3038 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003039 }
3040
Reid Spencer1628cec2006-10-26 06:15:43 +00003041 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3042 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003044 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003045 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003046 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003049 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003051 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003052 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003053 Op0, TC, SI->getName()+".t");
3054 TSI = InsertNewInstBefore(TSI, I);
3055
3056 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003057 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003058 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003059 Op0, FC, SI->getName()+".f");
3060 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003061
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003062 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003063 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003064 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003065 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003066 return 0;
3067}
3068
Reid Spencer1628cec2006-10-26 06:15:43 +00003069Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3070 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3071
3072 // Handle the integer div common cases
3073 if (Instruction *Common = commonIDivTransforms(I))
3074 return Common;
3075
3076 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3077 // sdiv X, -1 == -X
3078 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003079 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003080 }
3081
3082 // If the sign bits of both operands are zero (i.e. we can prove they are
3083 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003084 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003085 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003086 if (MaskedValueIsZero(Op0, Mask)) {
3087 if (MaskedValueIsZero(Op1, Mask)) {
3088 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3089 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090 }
3091 ConstantInt *ShiftedInt;
3092 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3093 ShiftedInt->getValue().isPowerOf2()) {
3094 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3095 // Safe because the only negative value (1 << Y) can take on is
3096 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3097 // the sign bit set.
3098 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3099 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003100 }
Eli Friedman8be17392009-07-18 09:53:21 +00003101 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003102
3103 return 0;
3104}
3105
3106Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3107 return commonDivTransforms(I);
3108}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003109
Reid Spencer0a783f72006-11-02 01:53:59 +00003110/// This function implements the transforms on rem instructions that work
3111/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3112/// is used by the visitors to those instructions.
3113/// @brief Transforms common to all three rem instructions
3114Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003116
Chris Lattner50b2ca42008-02-19 06:12:18 +00003117 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3118 if (I.getType()->isFPOrFPVector())
3119 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003120 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003121 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003122 if (isa<UndefValue>(Op1))
3123 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003124
3125 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003126 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3127 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003128
Reid Spencer0a783f72006-11-02 01:53:59 +00003129 return 0;
3130}
3131
3132/// This function implements the transforms common to both integer remainder
3133/// instructions (urem and srem). It is called by the visitors to those integer
3134/// remainder instructions.
3135/// @brief Common integer remainder transforms
3136Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3137 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3138
3139 if (Instruction *common = commonRemTransforms(I))
3140 return common;
3141
Dale Johannesened6af242009-01-21 00:35:19 +00003142 // 0 % X == 0 for integer, we don't need to preserve faults!
3143 if (Constant *LHS = dyn_cast<Constant>(Op0))
3144 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003145 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003146
Chris Lattner857e8cd2004-12-12 21:48:58 +00003147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003148 // X % 0 == undef, we don't need to preserve faults!
3149 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003150 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003151
Chris Lattnera2881962003-02-18 19:28:33 +00003152 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003153 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003154
Chris Lattner97943922006-02-28 05:49:21 +00003155 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3158 return R;
3159 } else if (isa<PHINode>(Op0I)) {
3160 if (Instruction *NV = FoldOpIntoPhi(I))
3161 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003162 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003163
3164 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003165 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003166 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003167 }
Chris Lattnera2881962003-02-18 19:28:33 +00003168 }
3169
Reid Spencer0a783f72006-11-02 01:53:59 +00003170 return 0;
3171}
3172
3173Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3174 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3175
3176 if (Instruction *common = commonIRemTransforms(I))
3177 return common;
3178
3179 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3180 // X urem C^2 -> X and C
3181 // Check to see if this is an unsigned remainder with an exact power of 2,
3182 // if so, convert to a bitwise and.
3183 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003184 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003185 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003186 }
3187
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003188 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003189 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3190 if (RHSI->getOpcode() == Instruction::Shl &&
3191 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003192 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003193 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003194 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003195 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003196 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003197 }
3198 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003200
Reid Spencer0a783f72006-11-02 01:53:59 +00003201 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3202 // where C1&C2 are powers of two.
3203 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3204 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3205 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3206 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003207 if ((STO->getValue().isPowerOf2()) &&
3208 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003210 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3211 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003213 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3214 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003215 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003216 }
3217 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003218 }
3219
Chris Lattner3f5b8772002-05-06 16:14:14 +00003220 return 0;
3221}
3222
Reid Spencer0a783f72006-11-02 01:53:59 +00003223Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3225
Dan Gohmancff55092007-11-05 23:16:33 +00003226 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003227 if (Instruction *common = commonIRemTransforms(I))
3228 return common;
3229
Owen Andersond672ecb2009-07-03 00:17:18 +00003230 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003231 if (!isa<Constant>(RHSNeg) ||
3232 (isa<ConstantInt>(RHSNeg) &&
3233 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003234 // X % -Y -> X % Y
3235 AddUsesToWorkList(I);
3236 I.setOperand(1, RHSNeg);
3237 return &I;
3238 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003239
Dan Gohmancff55092007-11-05 23:16:33 +00003240 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003241 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003242 if (I.getType()->isInteger()) {
3243 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3244 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3245 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003246 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003247 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003248 }
3249
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003250 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003251 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3252 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003253
Nick Lewycky9dce8732008-12-20 16:48:00 +00003254 bool hasNegative = false;
3255 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3256 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3257 if (RHS->getValue().isNegative())
3258 hasNegative = true;
3259
3260 if (hasNegative) {
3261 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003262 for (unsigned i = 0; i != VWidth; ++i) {
3263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3264 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003265 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003266 else
3267 Elts[i] = RHS;
3268 }
3269 }
3270
Owen Andersond672ecb2009-07-03 00:17:18 +00003271 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003272 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003273 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003274 I.setOperand(1, NewRHSV);
3275 return &I;
3276 }
3277 }
3278 }
3279
Reid Spencer0a783f72006-11-02 01:53:59 +00003280 return 0;
3281}
3282
3283Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003284 return commonRemTransforms(I);
3285}
3286
Chris Lattner457dd822004-06-09 07:59:58 +00003287// isOneBitSet - Return true if there is exactly one bit set in the specified
3288// constant.
3289static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003290 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003291}
3292
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003293// isHighOnes - Return true if the constant is of the form 1+0+.
3294// This is the same as lowones(~X).
3295static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003296 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003297}
3298
Reid Spencere4d87aa2006-12-23 06:05:41 +00003299/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003300/// are carefully arranged to allow folding of expressions such as:
3301///
3302/// (A < B) | (A > B) --> (A != B)
3303///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003304/// Note that this is only valid if the first and second predicates have the
3305/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003306///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003307/// Three bits are used to represent the condition, as follows:
3308/// 0 A > B
3309/// 1 A == B
3310/// 2 A < B
3311///
3312/// <=> Value Definition
3313/// 000 0 Always false
3314/// 001 1 A > B
3315/// 010 2 A == B
3316/// 011 3 A >= B
3317/// 100 4 A < B
3318/// 101 5 A != B
3319/// 110 6 A <= B
3320/// 111 7 Always true
3321///
3322static unsigned getICmpCode(const ICmpInst *ICI) {
3323 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003324 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325 case ICmpInst::ICMP_UGT: return 1; // 001
3326 case ICmpInst::ICMP_SGT: return 1; // 001
3327 case ICmpInst::ICMP_EQ: return 2; // 010
3328 case ICmpInst::ICMP_UGE: return 3; // 011
3329 case ICmpInst::ICMP_SGE: return 3; // 011
3330 case ICmpInst::ICMP_ULT: return 4; // 100
3331 case ICmpInst::ICMP_SLT: return 4; // 100
3332 case ICmpInst::ICMP_NE: return 5; // 101
3333 case ICmpInst::ICMP_ULE: return 6; // 110
3334 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003335 // True -> 7
3336 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003337 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003338 return 0;
3339 }
3340}
3341
Evan Cheng8db90722008-10-14 17:15:11 +00003342/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3343/// predicate into a three bit mask. It also returns whether it is an ordered
3344/// predicate by reference.
3345static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3346 isOrdered = false;
3347 switch (CC) {
3348 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3349 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003350 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3351 case FCmpInst::FCMP_UGT: return 1; // 001
3352 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3353 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003354 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3355 case FCmpInst::FCMP_UGE: return 3; // 011
3356 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3357 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003358 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3359 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003360 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3361 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003362 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003363 default:
3364 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003365 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003366 return 0;
3367 }
3368}
3369
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370/// getICmpValue - This is the complement of getICmpCode, which turns an
3371/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003372/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003373/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003374static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003375 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003377 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003378 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 case 1:
3380 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003381 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003382 else
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3384 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 case 3:
3386 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003387 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388 else
Owen Anderson333c4002009-07-09 23:48:35 +00003389 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 case 4:
3391 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003392 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 else
Owen Anderson333c4002009-07-09 23:48:35 +00003394 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3395 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 case 6:
3397 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003398 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 else
Owen Anderson333c4002009-07-09 23:48:35 +00003400 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003401 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003402 }
3403}
3404
Evan Cheng8db90722008-10-14 17:15:11 +00003405/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3406/// opcode and two operands into either a FCmp instruction. isordered is passed
3407/// in to determine which kind of predicate to use in the new fcmp instruction.
3408static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003409 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003410 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003411 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003412 case 0:
3413 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003414 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003415 else
Owen Anderson333c4002009-07-09 23:48:35 +00003416 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003417 case 1:
3418 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003419 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003420 else
Owen Anderson333c4002009-07-09 23:48:35 +00003421 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003422 case 2:
3423 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003424 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003425 else
Owen Anderson333c4002009-07-09 23:48:35 +00003426 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003427 case 3:
3428 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003429 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 else
Owen Anderson333c4002009-07-09 23:48:35 +00003431 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003432 case 4:
3433 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 else
Owen Anderson333c4002009-07-09 23:48:35 +00003436 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003437 case 5:
3438 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003440 else
Owen Anderson333c4002009-07-09 23:48:35 +00003441 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003442 case 6:
3443 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 else
Owen Anderson333c4002009-07-09 23:48:35 +00003446 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003447 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003448 }
3449}
3450
Chris Lattnerb9553d62008-11-16 04:55:20 +00003451/// PredicatesFoldable - Return true if both predicates match sign or if at
3452/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3454 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003455 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3456 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457}
3458
3459namespace {
3460// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3461struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003462 InstCombiner &IC;
3463 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003464 ICmpInst::Predicate pred;
3465 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3466 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3467 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003468 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003469 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3470 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003471 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3472 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003473 return false;
3474 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475 Instruction *apply(Instruction &Log) const {
3476 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3477 if (ICI->getOperand(0) != LHS) {
3478 assert(ICI->getOperand(1) == LHS);
3479 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003480 }
3481
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003482 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003484 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003485 unsigned Code;
3486 switch (Log.getOpcode()) {
3487 case Instruction::And: Code = LHSCode & RHSCode; break;
3488 case Instruction::Or: Code = LHSCode | RHSCode; break;
3489 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003490 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003491 }
3492
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003493 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3494 ICmpInst::isSignedPredicate(ICI->getPredicate());
3495
Owen Andersond672ecb2009-07-03 00:17:18 +00003496 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003497 if (Instruction *I = dyn_cast<Instruction>(RV))
3498 return I;
3499 // Otherwise, it's a constant boolean value...
3500 return IC.ReplaceInstUsesWith(Log, RV);
3501 }
3502};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003503} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003504
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3506// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003507// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003509 ConstantInt *OpRHS,
3510 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003511 BinaryOperator &TheAnd) {
3512 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003513 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003514 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003515 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003516
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003517 switch (Op->getOpcode()) {
3518 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003519 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003521 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003523 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003524 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003525 }
3526 break;
3527 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003528 if (Together == AndRHS) // (X | C) & C --> C
3529 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003530
Chris Lattner6e7ba452005-01-01 16:22:27 +00003531 if (Op->hasOneUse() && Together != OpRHS) {
3532 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003533 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003534 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003535 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003536 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 }
3538 break;
3539 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003540 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 // Adding a one to a single bit bit-field should be turned into an XOR
3542 // of the bit. First thing to check is to see if this AND is with a
3543 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003544 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545
3546 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003547 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548 // Ok, at this point, we know that we are masking the result of the
3549 // ADD down to exactly one bit. If the constant we are adding has
3550 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003551 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003552
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553 // Check to see if any bits below the one bit set in AndRHSV are set.
3554 if ((AddRHS & (AndRHSV-1)) == 0) {
3555 // If not, the only thing that can effect the output of the AND is
3556 // the bit specified by AndRHSV. If that bit is set, the effect of
3557 // the XOR is to toggle the bit. If it is clear, then the ADD has
3558 // no effect.
3559 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3560 TheAnd.setOperand(0, X);
3561 return &TheAnd;
3562 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003566 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003567 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 }
3569 }
3570 }
3571 }
3572 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003573
3574 case Instruction::Shl: {
3575 // We know that the AND will not produce any of the bits shifted in, so if
3576 // the anded constant includes them, clear them now!
3577 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003579 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003581 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003582
Zhou Sheng290bec52007-03-29 08:15:12 +00003583 if (CI->getValue() == ShlMask) {
3584 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003585 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3586 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003587 TheAnd.setOperand(1, CI);
3588 return &TheAnd;
3589 }
3590 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003591 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003592 case Instruction::LShr:
3593 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003594 // We know that the AND will not produce any of the bits shifted in, so if
3595 // the anded constant includes them, clear them now! This only applies to
3596 // unsigned shifts, because a signed shr may bring in set bits!
3597 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003599 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003601 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003602
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 if (CI->getValue() == ShrMask) {
3604 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003605 return ReplaceInstUsesWith(TheAnd, Op);
3606 } else if (CI != AndRHS) {
3607 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3608 return &TheAnd;
3609 }
3610 break;
3611 }
3612 case Instruction::AShr:
3613 // Signed shr.
3614 // See if this is shifting in some sign extension, then masking it out
3615 // with an and.
3616 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003617 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003618 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003620 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003621 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003622 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003623 // Make the argument unsigned.
3624 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003625 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003626 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003627 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003628 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003629 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003630 }
3631 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003632 }
3633 return 0;
3634}
3635
Chris Lattner8b170942002-08-09 23:47:40 +00003636
Chris Lattnera96879a2004-09-29 17:40:11 +00003637/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3638/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3640/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003641/// insert new instructions.
3642Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 bool isSigned, bool Inside,
3644 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003645 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003646 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003647 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648
Chris Lattnera96879a2004-09-29 17:40:11 +00003649 if (Inside) {
3650 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003651 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003652
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003654 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003655 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003657 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 }
3659
3660 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003661 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003662 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003663 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003664 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003665 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003666 }
3667
3668 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003669 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003670
Reid Spencere4e40032007-03-21 23:19:50 +00003671 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003672 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003673 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 ICmpInst::Predicate pred = (isSigned ?
3675 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003676 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003678
Reid Spencere4e40032007-03-21 23:19:50 +00003679 // Emit V-Lo >u Hi-1-Lo
3680 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003681 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003682 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003683 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003684 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003685 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003686}
3687
Chris Lattner7203e152005-09-18 07:22:02 +00003688// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3689// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3690// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3691// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003692static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003693 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003694 uint32_t BitWidth = Val->getType()->getBitWidth();
3695 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003696
3697 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003698 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003699 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003700 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003701 return true;
3702}
3703
Chris Lattner7203e152005-09-18 07:22:02 +00003704/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3705/// where isSub determines whether the operator is a sub. If we can fold one of
3706/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003707///
3708/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3709/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3710/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3711///
3712/// return (A +/- B).
3713///
3714Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003715 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003716 Instruction &I) {
3717 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3718 if (!LHSI || LHSI->getNumOperands() != 2 ||
3719 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3720
3721 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3722
3723 switch (LHSI->getOpcode()) {
3724 default: return 0;
3725 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003726 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003727 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003728 if ((Mask->getValue().countLeadingZeros() +
3729 Mask->getValue().countPopulation()) ==
3730 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003731 break;
3732
3733 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3734 // part, we don't need any explicit masks to take them out of A. If that
3735 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003736 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003737 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003738 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003739 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003740 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003741 break;
3742 }
3743 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003744 return 0;
3745 case Instruction::Or:
3746 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003747 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003748 if ((Mask->getValue().countLeadingZeros() +
3749 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003750 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003751 break;
3752 return 0;
3753 }
3754
3755 Instruction *New;
3756 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003757 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003759 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003760 return InsertNewInstBefore(New, I);
3761}
3762
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3764Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3765 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003766 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003767 ConstantInt *LHSCst, *RHSCst;
3768 ICmpInst::Predicate LHSCC, RHSCC;
3769
Chris Lattnerea065fb2008-11-16 05:10:52 +00003770 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003771 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3772 m_ConstantInt(LHSCst)), *Context) ||
3773 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3774 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003775 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003776
3777 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3778 // where C is a power of 2
3779 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3780 LHSCst->getValue().isPowerOf2()) {
3781 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3782 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003783 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003784 }
3785
3786 // From here on, we only handle:
3787 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3788 if (Val != Val2) return 0;
3789
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003790 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3791 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3792 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3793 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3794 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3795 return 0;
3796
3797 // We can't fold (ugt x, C) & (sgt x, C2).
3798 if (!PredicatesFoldable(LHSCC, RHSCC))
3799 return 0;
3800
3801 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 if (ICmpInst::isSignedPredicate(LHSCC) ||
3804 (ICmpInst::isEquality(LHSCC) &&
3805 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003806 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003808 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3809
3810 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811 std::swap(LHS, RHS);
3812 std::swap(LHSCst, RHSCst);
3813 std::swap(LHSCC, RHSCC);
3814 }
3815
3816 // At this point, we know we have have two icmp instructions
3817 // comparing a value against two constants and and'ing the result
3818 // together. Because of the above check, we know that we only have
3819 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3820 // (from the FoldICmpLogical check above), that the two constants
3821 // are not equal and that the larger constant is on the RHS
3822 assert(LHSCst != RHSCst && "Compares not folded above?");
3823
3824 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003825 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003826 case ICmpInst::ICMP_EQ:
3827 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003828 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3830 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3831 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003832 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003833 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3834 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3835 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3836 return ReplaceInstUsesWith(I, LHS);
3837 }
3838 case ICmpInst::ICMP_NE:
3839 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003840 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003842 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003843 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 break; // (X != 13 & X u< 15) -> no change
3845 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003846 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003847 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003848 break; // (X != 13 & X s< 15) -> no change
3849 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3850 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3851 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3852 return ReplaceInstUsesWith(I, RHS);
3853 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003854 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3855 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3857 Val->getName()+".off");
3858 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003859 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003860 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003861 }
3862 break; // (X != 13 & X != 15) -> no change
3863 }
3864 break;
3865 case ICmpInst::ICMP_ULT:
3866 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003867 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003868 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3869 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003870 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3872 break;
3873 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3874 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3875 return ReplaceInstUsesWith(I, LHS);
3876 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3877 break;
3878 }
3879 break;
3880 case ICmpInst::ICMP_SLT:
3881 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003882 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3884 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003885 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003886 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3887 break;
3888 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3889 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3890 return ReplaceInstUsesWith(I, LHS);
3891 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3892 break;
3893 }
3894 break;
3895 case ICmpInst::ICMP_UGT:
3896 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003897 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3899 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003904 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003905 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003907 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003908 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3909 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003910 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3911 break;
3912 }
3913 break;
3914 case ICmpInst::ICMP_SGT:
3915 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003916 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003917 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3918 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3919 return ReplaceInstUsesWith(I, RHS);
3920 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3921 break;
3922 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003923 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003924 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003926 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003927 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3928 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003929 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3930 break;
3931 }
3932 break;
3933 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003934
3935 return 0;
3936}
3937
Chris Lattner42d1be02009-07-23 05:14:02 +00003938Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3939 FCmpInst *RHS) {
3940
3941 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3942 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3943 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3944 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3945 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3946 // If either of the constants are nans, then the whole thing returns
3947 // false.
3948 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3949 return ReplaceInstUsesWith(I, Context->getFalse());
3950 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3951 LHS->getOperand(0), RHS->getOperand(0));
3952 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003953
3954 // Handle vector zeros. This occurs because the canonical form of
3955 // "fcmp ord x,x" is "fcmp ord x, 0".
3956 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3957 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3958 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3959 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003960 return 0;
3961 }
3962
3963 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3964 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3965 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3966
3967
3968 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3969 // Swap RHS operands to match LHS.
3970 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3971 std::swap(Op1LHS, Op1RHS);
3972 }
3973
3974 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3975 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3976 if (Op0CC == Op1CC)
3977 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3978
3979 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3980 return ReplaceInstUsesWith(I, Context->getFalse());
3981 if (Op0CC == FCmpInst::FCMP_TRUE)
3982 return ReplaceInstUsesWith(I, RHS);
3983 if (Op1CC == FCmpInst::FCMP_TRUE)
3984 return ReplaceInstUsesWith(I, LHS);
3985
3986 bool Op0Ordered;
3987 bool Op1Ordered;
3988 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3989 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3990 if (Op1Pred == 0) {
3991 std::swap(LHS, RHS);
3992 std::swap(Op0Pred, Op1Pred);
3993 std::swap(Op0Ordered, Op1Ordered);
3994 }
3995 if (Op0Pred == 0) {
3996 // uno && ueq -> uno && (uno || eq) -> ueq
3997 // ord && olt -> ord && (ord && lt) -> olt
3998 if (Op0Ordered == Op1Ordered)
3999 return ReplaceInstUsesWith(I, RHS);
4000
4001 // uno && oeq -> uno && (ord && eq) -> false
4002 // uno && ord -> false
4003 if (!Op0Ordered)
4004 return ReplaceInstUsesWith(I, Context->getFalse());
4005 // ord && ueq -> ord && (uno || eq) -> oeq
4006 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4007 Op0LHS, Op0RHS, Context));
4008 }
4009 }
4010
4011 return 0;
4012}
4013
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004014
Chris Lattner7e708292002-06-25 16:13:24 +00004015Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004016 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004018
Chris Lattnere87597f2004-10-16 18:11:37 +00004019 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004020 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004021
Chris Lattner6e7ba452005-01-01 16:22:27 +00004022 // and X, X = X
4023 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004024 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004025
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004026 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004027 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004028 if (SimplifyDemandedInstructionBits(I))
4029 return &I;
4030 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004031 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004032 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004033 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004034 } else if (isa<ConstantAggregateZero>(Op1)) {
4035 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004036 }
4037 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004038
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004039 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004040 const APInt& AndRHSMask = AndRHS->getValue();
4041 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004042
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004043 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004044 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004045 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004046 Value *Op0LHS = Op0I->getOperand(0);
4047 Value *Op0RHS = Op0I->getOperand(1);
4048 switch (Op0I->getOpcode()) {
4049 case Instruction::Xor:
4050 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004051 // If the mask is only needed on one incoming arm, push it up.
4052 if (Op0I->hasOneUse()) {
4053 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4054 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004055 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 Op0RHS->getName()+".masked");
4057 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004058 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004059 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004060 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004061 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004062 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4063 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004064 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004065 Op0LHS->getName()+".masked");
4066 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004067 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004068 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4069 }
4070 }
4071
Chris Lattner6e7ba452005-01-01 16:22:27 +00004072 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004073 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004074 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4075 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4076 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4077 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004078 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004079 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004081 break;
4082
4083 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004084 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4085 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4086 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4087 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004089
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004090 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4091 // has 1's for all bits that the subtraction with A might affect.
4092 if (Op0I->hasOneUse()) {
4093 uint32_t BitWidth = AndRHSMask.getBitWidth();
4094 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4095 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4096
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004097 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004098 if (!(A && A->isZero()) && // avoid infinite recursion.
4099 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004100 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004101 InsertNewInstBefore(NewNeg, I);
4102 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4103 }
4104 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004105 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004106
4107 case Instruction::Shl:
4108 case Instruction::LShr:
4109 // (1 << x) & 1 --> zext(x == 0)
4110 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004111 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004112 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4113 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004114 InsertNewInstBefore(NewICmp, I);
4115 return new ZExtInst(NewICmp, I.getType());
4116 }
4117 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004118 }
4119
Chris Lattner58403262003-07-23 19:25:52 +00004120 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004121 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004122 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004123 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004124 // If this is an integer truncation or change from signed-to-unsigned, and
4125 // if the source is an and/or with immediate, transform it. This
4126 // frequently occurs for bitfield accesses.
4127 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004128 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004130 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004131 if (CastOp->getOpcode() == Instruction::And) {
4132 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004133 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4134 // This will fold the two constants together, which may allow
4135 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004136 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004137 CastOp->getOperand(0), I.getType(),
4138 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004139 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004140 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004141 Constant *C3 =
4142 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4143 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004144 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004145 } else if (CastOp->getOpcode() == Instruction::Or) {
4146 // Change: and (cast (or X, C1) to T), C2
4147 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004148 Constant *C3 =
4149 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4150 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4151 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004152 return ReplaceInstUsesWith(I, AndRHS);
4153 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004154 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004155 }
Chris Lattner06782f82003-07-23 19:36:21 +00004156 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004157
4158 // Try to fold constant and into select arguments.
4159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004161 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004162 if (isa<PHINode>(Op0))
4163 if (Instruction *NV = FoldOpIntoPhi(I))
4164 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004165 }
4166
Owen Andersond672ecb2009-07-03 00:17:18 +00004167 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4168 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004169
Chris Lattner5b62aa72004-06-18 06:07:51 +00004170 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004171 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004172
Misha Brukmancb6267b2004-07-30 12:50:08 +00004173 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004174 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004175 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004176 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004177 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004178 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004179 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004180
4181 {
Chris Lattner003b6202007-06-15 05:58:24 +00004182 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004183 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004184 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4185 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004186
4187 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004188 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004189 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004190 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004191 }
4192 }
4193
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004194 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004195 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4196 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004197
4198 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004199 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004200 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004201 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004202 }
4203 }
Chris Lattner64daab52006-04-01 08:03:55 +00004204
4205 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004206 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004207 if (A == Op1) { // (A^B)&A -> A&(A^B)
4208 I.swapOperands(); // Simplify below
4209 std::swap(Op0, Op1);
4210 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4211 cast<BinaryOperator>(Op0)->swapOperands();
4212 I.swapOperands(); // Simplify below
4213 std::swap(Op0, Op1);
4214 }
4215 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004216
Chris Lattner64daab52006-04-01 08:03:55 +00004217 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004218 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004219 if (B == Op0) { // B&(A^B) -> B&(B^A)
4220 cast<BinaryOperator>(Op1)->swapOperands();
4221 std::swap(A, B);
4222 }
4223 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004224 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004225 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004226 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004227 }
4228 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004229
4230 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004231 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4232 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004233 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004234 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4235 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004236 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004237 }
4238
Reid Spencere4d87aa2006-12-23 06:05:41 +00004239 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4240 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004241 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004242 return R;
4243
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004244 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4245 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4246 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004247 }
4248
Chris Lattner6fc205f2006-05-05 06:39:07 +00004249 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004250 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4251 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4252 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4253 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004254 if (SrcTy == Op1C->getOperand(0)->getType() &&
4255 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004256 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004257 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4258 I.getType(), TD) &&
4259 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4260 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004261 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004262 Op1C->getOperand(0),
4263 I.getName());
4264 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004266 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004267 }
Chris Lattnere511b742006-11-14 07:46:50 +00004268
4269 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004270 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4271 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4272 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004273 SI0->getOperand(1) == SI1->getOperand(1) &&
4274 (SI0->hasOneUse() || SI1->hasOneUse())) {
4275 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004276 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004277 SI1->getOperand(0),
4278 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004279 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004280 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004281 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004282 }
4283
Evan Cheng8db90722008-10-14 17:15:11 +00004284 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004285 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004286 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4287 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4288 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004289 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004290
Chris Lattner7e708292002-06-25 16:13:24 +00004291 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004292}
4293
Chris Lattner8c34cd22008-10-05 02:13:19 +00004294/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4295/// capable of providing pieces of a bswap. The subexpression provides pieces
4296/// of a bswap if it is proven that each of the non-zero bytes in the output of
4297/// the expression came from the corresponding "byte swapped" byte in some other
4298/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4299/// we know that the expression deposits the low byte of %X into the high byte
4300/// of the bswap result and that all other bytes are zero. This expression is
4301/// accepted, the high byte of ByteValues is set to X to indicate a correct
4302/// match.
4303///
4304/// This function returns true if the match was unsuccessful and false if so.
4305/// On entry to the function the "OverallLeftShift" is a signed integer value
4306/// indicating the number of bytes that the subexpression is later shifted. For
4307/// example, if the expression is later right shifted by 16 bits, the
4308/// OverallLeftShift value would be -2 on entry. This is used to specify which
4309/// byte of ByteValues is actually being set.
4310///
4311/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4312/// byte is masked to zero by a user. For example, in (X & 255), X will be
4313/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4314/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4315/// always in the local (OverallLeftShift) coordinate space.
4316///
4317static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4318 SmallVector<Value*, 8> &ByteValues) {
4319 if (Instruction *I = dyn_cast<Instruction>(V)) {
4320 // If this is an or instruction, it may be an inner node of the bswap.
4321 if (I->getOpcode() == Instruction::Or) {
4322 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4323 ByteValues) ||
4324 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4325 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004326 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004327
4328 // If this is a logical shift by a constant multiple of 8, recurse with
4329 // OverallLeftShift and ByteMask adjusted.
4330 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4331 unsigned ShAmt =
4332 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4333 // Ensure the shift amount is defined and of a byte value.
4334 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4335 return true;
4336
4337 unsigned ByteShift = ShAmt >> 3;
4338 if (I->getOpcode() == Instruction::Shl) {
4339 // X << 2 -> collect(X, +2)
4340 OverallLeftShift += ByteShift;
4341 ByteMask >>= ByteShift;
4342 } else {
4343 // X >>u 2 -> collect(X, -2)
4344 OverallLeftShift -= ByteShift;
4345 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004346 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004347 }
4348
4349 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4350 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4351
4352 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 ByteValues);
4354 }
4355
4356 // If this is a logical 'and' with a mask that clears bytes, clear the
4357 // corresponding bytes in ByteMask.
4358 if (I->getOpcode() == Instruction::And &&
4359 isa<ConstantInt>(I->getOperand(1))) {
4360 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4361 unsigned NumBytes = ByteValues.size();
4362 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4363 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4364
4365 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4366 // If this byte is masked out by a later operation, we don't care what
4367 // the and mask is.
4368 if ((ByteMask & (1 << i)) == 0)
4369 continue;
4370
4371 // If the AndMask is all zeros for this byte, clear the bit.
4372 APInt MaskB = AndMask & Byte;
4373 if (MaskB == 0) {
4374 ByteMask &= ~(1U << i);
4375 continue;
4376 }
4377
4378 // If the AndMask is not all ones for this byte, it's not a bytezap.
4379 if (MaskB != Byte)
4380 return true;
4381
4382 // Otherwise, this byte is kept.
4383 }
4384
4385 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4386 ByteValues);
4387 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004388 }
4389
Chris Lattner8c34cd22008-10-05 02:13:19 +00004390 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4391 // the input value to the bswap. Some observations: 1) if more than one byte
4392 // is demanded from this input, then it could not be successfully assembled
4393 // into a byteswap. At least one of the two bytes would not be aligned with
4394 // their ultimate destination.
4395 if (!isPowerOf2_32(ByteMask)) return true;
4396 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004397
Chris Lattner8c34cd22008-10-05 02:13:19 +00004398 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4399 // is demanded, it needs to go into byte 0 of the result. This means that the
4400 // byte needs to be shifted until it lands in the right byte bucket. The
4401 // shift amount depends on the position: if the byte is coming from the high
4402 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4403 // low part, it must be shifted left.
4404 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4405 if (InputByteNo < ByteValues.size()/2) {
4406 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4407 return true;
4408 } else {
4409 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4410 return true;
4411 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412
4413 // If the destination byte value is already defined, the values are or'd
4414 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004416 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004417 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004418 return false;
4419}
4420
4421/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4422/// If so, insert the new bswap intrinsic and return it.
4423Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004424 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004425 if (!ITy || ITy->getBitWidth() % 16 ||
4426 // ByteMask only allows up to 32-byte values.
4427 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004428 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429
4430 /// ByteValues - For each byte of the result, we keep track of which value
4431 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004432 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004433 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004434
4435 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004436 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4437 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438 return 0;
4439
4440 // Check to see if all of the bytes come from the same value.
4441 Value *V = ByteValues[0];
4442 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4443
4444 // Check to make sure that all of the bytes come from the same value.
4445 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4446 if (ByteValues[i] != V)
4447 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004448 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004450 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004451 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004452}
4453
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004454/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4455/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4456/// we can simplify this expression to "cond ? C : D or B".
4457static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004458 Value *C, Value *D,
4459 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004460 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004461 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004462 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004463 return 0;
4464
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004466 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004467 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004468 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004469 return SelectInst::Create(Cond, C, B);
4470 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004471 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004472 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004473 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004474 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004475 return 0;
4476}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004477
Chris Lattner69d4ced2008-11-16 05:20:07 +00004478/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4479Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4480 ICmpInst *LHS, ICmpInst *RHS) {
4481 Value *Val, *Val2;
4482 ConstantInt *LHSCst, *RHSCst;
4483 ICmpInst::Predicate LHSCC, RHSCC;
4484
4485 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004486 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4487 m_ConstantInt(LHSCst)), *Context) ||
4488 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4489 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004490 return 0;
4491
4492 // From here on, we only handle:
4493 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4494 if (Val != Val2) return 0;
4495
4496 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4497 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4498 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4499 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4500 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4501 return 0;
4502
4503 // We can't fold (ugt x, C) | (sgt x, C2).
4504 if (!PredicatesFoldable(LHSCC, RHSCC))
4505 return 0;
4506
4507 // Ensure that the larger constant is on the RHS.
4508 bool ShouldSwap;
4509 if (ICmpInst::isSignedPredicate(LHSCC) ||
4510 (ICmpInst::isEquality(LHSCC) &&
4511 ICmpInst::isSignedPredicate(RHSCC)))
4512 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4513 else
4514 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4515
4516 if (ShouldSwap) {
4517 std::swap(LHS, RHS);
4518 std::swap(LHSCst, RHSCst);
4519 std::swap(LHSCC, RHSCC);
4520 }
4521
4522 // At this point, we know we have have two icmp instructions
4523 // comparing a value against two constants and or'ing the result
4524 // together. Because of the above check, we know that we only have
4525 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4526 // FoldICmpLogical check above), that the two constants are not
4527 // equal.
4528 assert(LHSCst != RHSCst && "Compares not folded above?");
4529
4530 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004531 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532 case ICmpInst::ICMP_EQ:
4533 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004534 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004535 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004536 if (LHSCst == SubOne(RHSCst, Context)) {
4537 // (X == 13 | X == 14) -> X-13 <u 2
4538 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004539 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4540 Val->getName()+".off");
4541 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004542 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004543 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 }
4545 break; // (X == 13 | X == 15) -> no change
4546 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4547 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4548 break;
4549 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4550 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4551 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4552 return ReplaceInstUsesWith(I, RHS);
4553 }
4554 break;
4555 case ICmpInst::ICMP_NE:
4556 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004557 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004558 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4559 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4560 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4561 return ReplaceInstUsesWith(I, LHS);
4562 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4563 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4564 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004565 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004566 }
4567 break;
4568 case ICmpInst::ICMP_ULT:
4569 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004570 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4572 break;
4573 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4574 // If RHSCst is [us]MAXINT, it is always false. Not handling
4575 // this can cause overflow.
4576 if (RHSCst->isMaxValue(false))
4577 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004578 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4579 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4583 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4584 return ReplaceInstUsesWith(I, RHS);
4585 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4586 break;
4587 }
4588 break;
4589 case ICmpInst::ICMP_SLT:
4590 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004591 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4593 break;
4594 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4595 // If RHSCst is [us]MAXINT, it is always false. Not handling
4596 // this can cause overflow.
4597 if (RHSCst->isMaxValue(true))
4598 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004599 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4600 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004601 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4602 break;
4603 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4604 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4605 return ReplaceInstUsesWith(I, RHS);
4606 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4607 break;
4608 }
4609 break;
4610 case ICmpInst::ICMP_UGT:
4611 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004612 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004613 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4614 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4615 return ReplaceInstUsesWith(I, LHS);
4616 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4617 break;
4618 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4619 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004620 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004621 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4622 break;
4623 }
4624 break;
4625 case ICmpInst::ICMP_SGT:
4626 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004627 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004628 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4629 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4630 return ReplaceInstUsesWith(I, LHS);
4631 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4632 break;
4633 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4634 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004635 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004636 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4637 break;
4638 }
4639 break;
4640 }
4641 return 0;
4642}
4643
Chris Lattner5414cc52009-07-23 05:46:22 +00004644Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4645 FCmpInst *RHS) {
4646 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4647 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4648 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4649 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4650 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4651 // If either of the constants are nans, then the whole thing returns
4652 // true.
4653 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4654 return ReplaceInstUsesWith(I, Context->getTrue());
4655
4656 // Otherwise, no need to compare the two constants, compare the
4657 // rest.
4658 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4659 LHS->getOperand(0), RHS->getOperand(0));
4660 }
4661
4662 // Handle vector zeros. This occurs because the canonical form of
4663 // "fcmp uno x,x" is "fcmp uno x, 0".
4664 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4665 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4666 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4667 LHS->getOperand(0), RHS->getOperand(0));
4668
4669 return 0;
4670 }
4671
4672 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4673 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4674 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4675
4676 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4677 // Swap RHS operands to match LHS.
4678 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4679 std::swap(Op1LHS, Op1RHS);
4680 }
4681 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4682 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4683 if (Op0CC == Op1CC)
4684 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4685 Op0LHS, Op0RHS);
4686 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4687 return ReplaceInstUsesWith(I, Context->getTrue());
4688 if (Op0CC == FCmpInst::FCMP_FALSE)
4689 return ReplaceInstUsesWith(I, RHS);
4690 if (Op1CC == FCmpInst::FCMP_FALSE)
4691 return ReplaceInstUsesWith(I, LHS);
4692 bool Op0Ordered;
4693 bool Op1Ordered;
4694 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4695 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4696 if (Op0Ordered == Op1Ordered) {
4697 // If both are ordered or unordered, return a new fcmp with
4698 // or'ed predicates.
4699 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4700 Op0LHS, Op0RHS, Context);
4701 if (Instruction *I = dyn_cast<Instruction>(RV))
4702 return I;
4703 // Otherwise, it's a constant boolean value...
4704 return ReplaceInstUsesWith(I, RV);
4705 }
4706 }
4707 return 0;
4708}
4709
Bill Wendlinga698a472008-12-01 08:23:25 +00004710/// FoldOrWithConstants - This helper function folds:
4711///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004712/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004713///
4714/// into:
4715///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004716/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004717///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004718/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004719Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004720 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004721 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4722 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004723
Bill Wendling286a0542008-12-02 06:24:20 +00004724 Value *V1 = 0;
4725 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004726 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004727
Bill Wendling29976b92008-12-02 06:18:11 +00004728 APInt Xor = CI1->getValue() ^ CI2->getValue();
4729 if (!Xor.isAllOnesValue()) return 0;
4730
Bill Wendling286a0542008-12-02 06:24:20 +00004731 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004732 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004733 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4734 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004735 }
4736
4737 return 0;
4738}
4739
Chris Lattner7e708292002-06-25 16:13:24 +00004740Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004741 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004743
Chris Lattner42593e62007-03-24 23:56:43 +00004744 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004745 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004746
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004747 // or X, X = X
4748 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004749 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004750
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004751 // See if we can simplify any instructions used by the instruction whose sole
4752 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004753 if (SimplifyDemandedInstructionBits(I))
4754 return &I;
4755 if (isa<VectorType>(I.getType())) {
4756 if (isa<ConstantAggregateZero>(Op1)) {
4757 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4758 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4759 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4760 return ReplaceInstUsesWith(I, I.getOperand(1));
4761 }
Chris Lattner42593e62007-03-24 23:56:43 +00004762 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004763
Chris Lattner3f5b8772002-05-06 16:14:14 +00004764 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004765 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004766 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004767 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004768 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4769 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004770 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004771 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004772 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004774 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004775 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004776
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004777 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004778 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4779 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004780 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004781 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004782 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004783 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004784 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004785 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004786
4787 // Try to fold constant and into select arguments.
4788 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004789 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004790 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004791 if (isa<PHINode>(Op0))
4792 if (Instruction *NV = FoldOpIntoPhi(I))
4793 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004794 }
4795
Chris Lattner4f637d42006-01-06 17:59:59 +00004796 Value *A = 0, *B = 0;
4797 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004798
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004799 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004800 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4801 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004803 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4804 return ReplaceInstUsesWith(I, Op0);
4805
Chris Lattner6423d4c2006-07-10 20:25:24 +00004806 // (A | B) | C and A | (B | C) -> bswap if possible.
4807 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004808 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4809 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4810 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4811 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004812 if (Instruction *BSwap = MatchBSwap(I))
4813 return BSwap;
4814 }
4815
Chris Lattner6e4c6492005-05-09 04:58:36 +00004816 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004817 if (Op0->hasOneUse() &&
4818 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004819 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004820 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004821 InsertNewInstBefore(NOr, I);
4822 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004823 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004824 }
4825
4826 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004827 if (Op1->hasOneUse() &&
4828 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004829 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004830 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004831 InsertNewInstBefore(NOr, I);
4832 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004833 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004834 }
4835
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004836 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004837 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004838 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4839 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004840 Value *V1 = 0, *V2 = 0, *V3 = 0;
4841 C1 = dyn_cast<ConstantInt>(C);
4842 C2 = dyn_cast<ConstantInt>(D);
4843 if (C1 && C2) { // (A & C1)|(B & C2)
4844 // If we have: ((V + N) & C1) | (V & C2)
4845 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4846 // replace with V+N.
4847 if (C1->getValue() == ~C2->getValue()) {
4848 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004849 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004850 // Add commutes, try both ways.
4851 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4852 return ReplaceInstUsesWith(I, A);
4853 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4854 return ReplaceInstUsesWith(I, A);
4855 }
4856 // Or commutes, try both ways.
4857 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004858 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004859 // Add commutes, try both ways.
4860 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4861 return ReplaceInstUsesWith(I, B);
4862 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4863 return ReplaceInstUsesWith(I, B);
4864 }
4865 }
Chris Lattner044e5332007-04-08 08:01:49 +00004866 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004867 }
4868
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004869 // Check to see if we have any common things being and'ed. If so, find the
4870 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004871 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4872 if (A == B) // (A & C)|(A & D) == A & (C|D)
4873 V1 = A, V2 = C, V3 = D;
4874 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4875 V1 = A, V2 = B, V3 = C;
4876 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4877 V1 = C, V2 = A, V3 = D;
4878 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4879 V1 = C, V2 = A, V3 = B;
4880
4881 if (V1) {
4882 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004883 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4884 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004885 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004886 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004887
Dan Gohman1975d032008-10-30 20:40:10 +00004888 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004889 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004890 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004891 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004892 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004893 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004894 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004895 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004896 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004897
Bill Wendlingb01865c2008-11-30 13:52:49 +00004898 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004899 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4900 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004901 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004902 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004903 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4904 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004905 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004906 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004907 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4908 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004909 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004910 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004911 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4912 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004913 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004914 }
Chris Lattnere511b742006-11-14 07:46:50 +00004915
4916 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004917 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4918 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4919 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004920 SI0->getOperand(1) == SI1->getOperand(1) &&
4921 (SI0->hasOneUse() || SI1->hasOneUse())) {
4922 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004923 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004924 SI1->getOperand(0),
4925 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004926 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004927 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004928 }
4929 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004930
Bill Wendlingb3833d12008-12-01 01:07:11 +00004931 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004932 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4933 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004934 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004935 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004936 }
4937 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004938 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4939 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004940 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004941 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004942 }
4943
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004944 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004945 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004946 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004947 } else {
4948 A = 0;
4949 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004950 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004951 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004952 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004953 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004954
Misha Brukmancb6267b2004-07-30 12:50:08 +00004955 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004956 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004957 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004958 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004959 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004960 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004961 }
Chris Lattnera2881962003-02-18 19:28:33 +00004962
Reid Spencere4d87aa2006-12-23 06:05:41 +00004963 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4964 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004965 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004966 return R;
4967
Chris Lattner69d4ced2008-11-16 05:20:07 +00004968 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4969 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4970 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004971 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004972
4973 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004974 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004975 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004976 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004977 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4978 !isa<ICmpInst>(Op1C->getOperand(0))) {
4979 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004980 if (SrcTy == Op1C->getOperand(0)->getType() &&
4981 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004982 // Only do this if the casts both really cause code to be
4983 // generated.
4984 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4985 I.getType(), TD) &&
4986 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4987 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004988 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004989 Op1C->getOperand(0),
4990 I.getName());
4991 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004992 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004993 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004994 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004995 }
Chris Lattner99c65742007-10-24 05:38:08 +00004996 }
4997
4998
4999 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5000 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005001 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5002 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5003 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005004 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005005
Chris Lattner7e708292002-06-25 16:13:24 +00005006 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005007}
5008
Dan Gohman844731a2008-05-13 00:00:25 +00005009namespace {
5010
Chris Lattnerc317d392004-02-16 01:20:27 +00005011// XorSelf - Implements: X ^ X --> 0
5012struct XorSelf {
5013 Value *RHS;
5014 XorSelf(Value *rhs) : RHS(rhs) {}
5015 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5016 Instruction *apply(BinaryOperator &Xor) const {
5017 return &Xor;
5018 }
5019};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005020
Dan Gohman844731a2008-05-13 00:00:25 +00005021}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022
Chris Lattner7e708292002-06-25 16:13:24 +00005023Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005024 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005026
Evan Chengd34af782008-03-25 20:07:13 +00005027 if (isa<UndefValue>(Op1)) {
5028 if (isa<UndefValue>(Op0))
5029 // Handle undef ^ undef -> 0 special case. This is a common
5030 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005031 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005032 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005033 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005034
Chris Lattnerc317d392004-02-16 01:20:27 +00005035 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005036 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005037 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005038 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005039 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005040
5041 // See if we can simplify any instructions used by the instruction whose sole
5042 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005043 if (SimplifyDemandedInstructionBits(I))
5044 return &I;
5045 if (isa<VectorType>(I.getType()))
5046 if (isa<ConstantAggregateZero>(Op1))
5047 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005048
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005049 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005050 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005051 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5052 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5054 if (Op0I->getOpcode() == Instruction::And ||
5055 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005056 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5057 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005059 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 Op0I->getOperand(1)->getName()+".not");
5061 InsertNewInstBefore(NotY, I);
5062 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005064 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005065 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 }
5067 }
5068 }
5069 }
5070
5071
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005073 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005074 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005076 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005078
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005079 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005080 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005081 FCI->getOperand(0), FCI->getOperand(1));
5082 }
5083
Nick Lewycky517e1f52008-05-31 19:01:33 +00005084 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5085 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5086 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5087 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5088 Instruction::CastOps Opcode = Op0C->getOpcode();
5089 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005090 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005091 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005092 Op0C->getDestTy())) {
5093 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005094 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005095 CI->getOpcode(), CI->getInversePredicate(),
5096 CI->getOperand(0), CI->getOperand(1)), I);
5097 NewCI->takeName(CI);
5098 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5099 }
5100 }
5101 }
5102 }
5103 }
5104
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005106 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005107 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5108 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005109 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5110 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005111 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005113 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005114
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005115 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005116 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005117 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005118 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005119 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005121 Context->getConstantExprSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005122 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005123 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005124 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005125 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005126 Constant *C = ConstantInt::get(*Context,
5127 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005129
Chris Lattner7c4049c2004-01-12 19:35:11 +00005130 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005131 } else if (Op0I->getOpcode() == Instruction::Or) {
5132 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005133 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005134 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005135 // Anything in both C1 and C2 is known to be zero, remove it from
5136 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005137 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5138 NewRHS = Context->getConstantExprAnd(NewRHS,
5139 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005140 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005141 I.setOperand(0, Op0I->getOperand(0));
5142 I.setOperand(1, NewRHS);
5143 return &I;
5144 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005145 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005146 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005148
5149 // Try to fold constant and into select arguments.
5150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005153 if (isa<PHINode>(Op0))
5154 if (Instruction *NV = FoldOpIntoPhi(I))
5155 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005156 }
5157
Owen Andersond672ecb2009-07-03 00:17:18 +00005158 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005159 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005160 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005161
Owen Andersond672ecb2009-07-03 00:17:18 +00005162 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005163 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005164 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005165
Chris Lattner318bf792007-03-18 22:51:34 +00005166
5167 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5168 if (Op1I) {
5169 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005170 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005171 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005172 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005173 I.swapOperands();
5174 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005175 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005176 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005177 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005178 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005180 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005181 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005182 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005183 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5184 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005185 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005186 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005187 std::swap(A, B);
5188 }
Chris Lattner318bf792007-03-18 22:51:34 +00005189 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005190 I.swapOperands(); // Simplified below.
5191 std::swap(Op0, Op1);
5192 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005193 }
Chris Lattner318bf792007-03-18 22:51:34 +00005194 }
5195
5196 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5197 if (Op0I) {
5198 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005199 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5200 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005201 if (A == Op1) // (B|A)^B == (A|B)^B
5202 std::swap(A, B);
5203 if (B == Op1) { // (A|B)^B == A & ~B
5204 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005205 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5206 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005208 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005210 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005211 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005212 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005213 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5214 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005215 if (A == Op1) // (A&B)^A -> (B&A)^A
5216 std::swap(A, B);
5217 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005218 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005219 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005220 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005221 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005222 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005223 }
Chris Lattner318bf792007-03-18 22:51:34 +00005224 }
5225
5226 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5227 if (Op0I && Op1I && Op0I->isShift() &&
5228 Op0I->getOpcode() == Op1I->getOpcode() &&
5229 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5230 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5231 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005233 Op1I->getOperand(0),
5234 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005235 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005236 Op1I->getOperand(1));
5237 }
5238
5239 if (Op0I && Op1I) {
5240 Value *A, *B, *C, *D;
5241 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005242 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5243 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005244 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005246 }
5247 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005248 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5249 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005250 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005251 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005252 }
5253
5254 // (A & B)^(C & D)
5255 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005256 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5257 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005258 // (X & Y)^(X & Y) -> (Y^Z) & X
5259 Value *X = 0, *Y = 0, *Z = 0;
5260 if (A == C)
5261 X = A, Y = B, Z = D;
5262 else if (A == D)
5263 X = A, Y = B, Z = C;
5264 else if (B == C)
5265 X = B, Y = A, Z = D;
5266 else if (B == D)
5267 X = B, Y = A, Z = C;
5268
5269 if (X) {
5270 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005271 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5272 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005273 }
5274 }
5275 }
5276
Reid Spencere4d87aa2006-12-23 06:05:41 +00005277 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5278 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005279 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005280 return R;
5281
Chris Lattner6fc205f2006-05-05 06:39:07 +00005282 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005283 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005284 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005285 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5286 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005287 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005288 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005289 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5290 I.getType(), TD) &&
5291 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5292 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005293 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005294 Op1C->getOperand(0),
5295 I.getName());
5296 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005297 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005298 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005299 }
Chris Lattner99c65742007-10-24 05:38:08 +00005300 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005301
Chris Lattner7e708292002-06-25 16:13:24 +00005302 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005303}
5304
Owen Andersond672ecb2009-07-03 00:17:18 +00005305static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005306 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005307 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005308}
Chris Lattnera96879a2004-09-29 17:40:11 +00005309
Dan Gohman6de29f82009-06-15 22:12:54 +00005310static bool HasAddOverflow(ConstantInt *Result,
5311 ConstantInt *In1, ConstantInt *In2,
5312 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005313 if (IsSigned)
5314 if (In2->getValue().isNegative())
5315 return Result->getValue().sgt(In1->getValue());
5316 else
5317 return Result->getValue().slt(In1->getValue());
5318 else
5319 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005320}
5321
Dan Gohman6de29f82009-06-15 22:12:54 +00005322/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005323/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005324static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005325 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005326 bool IsSigned = false) {
5327 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005328
Dan Gohman6de29f82009-06-15 22:12:54 +00005329 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005331 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005332 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333 ExtractElement(In1, Idx, Context),
5334 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005335 IsSigned))
5336 return true;
5337 }
5338 return false;
5339 }
5340
5341 return HasAddOverflow(cast<ConstantInt>(Result),
5342 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343 IsSigned);
5344}
5345
5346static bool HasSubOverflow(ConstantInt *Result,
5347 ConstantInt *In1, ConstantInt *In2,
5348 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005349 if (IsSigned)
5350 if (In2->getValue().isNegative())
5351 return Result->getValue().slt(In1->getValue());
5352 else
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().ugt(In1->getValue());
5356}
5357
Dan Gohman6de29f82009-06-15 22:12:54 +00005358/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359/// overflowed for this type.
5360static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005361 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005362 bool IsSigned = false) {
5363 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005364
5365 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005367 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005368 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369 ExtractElement(In1, Idx, Context),
5370 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005371 IsSigned))
5372 return true;
5373 }
5374 return false;
5375 }
5376
5377 return HasSubOverflow(cast<ConstantInt>(Result),
5378 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379 IsSigned);
5380}
5381
Chris Lattner574da9b2005-01-13 20:14:25 +00005382/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383/// code necessary to compute the offset from the base pointer (without adding
5384/// in the base pointer). Return the result as a signed integer of intptr size.
5385static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005386 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005387 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005389 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005390 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005391
5392 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005393 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005394 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005395
Gabor Greif177dd3f2008-06-12 21:37:33 +00005396 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5397 ++i, ++GTI) {
5398 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005399 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005400 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5401 if (OpC->isZero()) continue;
5402
5403 // Handle a struct index, which adds its field offset to the pointer.
5404 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5405 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5406
5407 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005408 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005409 ConstantInt::get(*Context,
5410 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005411 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005413 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005414 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 GEP->getName()+".offs"), I);
5416 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005417 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005418
Owen Andersoneed707b2009-07-24 23:12:02 +00005419 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005420 Constant *OC =
5421 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5422 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005424 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 else {
5426 // Emit an add instruction.
5427 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005428 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005429 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005430 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005432 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005433 // Convert to correct type.
5434 if (Op->getType() != IntPtrTy) {
5435 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005436 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005438 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5439 true,
5440 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005441 }
5442 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005443 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005445 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005447 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005448 GEP->getName()+".idx"), I);
5449 }
5450
5451 // Emit an add instruction.
5452 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005453 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005454 cast<Constant>(Result));
5455 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005456 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005457 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005458 }
5459 return Result;
5460}
5461
Chris Lattner10c0d912008-04-22 02:53:33 +00005462
Dan Gohman8f080f02009-07-17 22:16:21 +00005463/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5464/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5465/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5466/// be complex, and scales are involved. The above expression would also be
5467/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5468/// This later form is less amenable to optimization though, and we are allowed
5469/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005470///
5471/// If we can't emit an optimized form for this expression, this returns null.
5472///
5473static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5474 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005475 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005476 gep_type_iterator GTI = gep_type_begin(GEP);
5477
5478 // Check to see if this gep only has a single variable index. If so, and if
5479 // any constant indices are a multiple of its scale, then we can compute this
5480 // in terms of the scale of the variable index. For example, if the GEP
5481 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5482 // because the expression will cross zero at the same point.
5483 unsigned i, e = GEP->getNumOperands();
5484 int64_t Offset = 0;
5485 for (i = 1; i != e; ++i, ++GTI) {
5486 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5487 // Compute the aggregate offset of constant indices.
5488 if (CI->isZero()) continue;
5489
5490 // Handle a struct index, which adds its field offset to the pointer.
5491 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5492 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5493 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005494 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005495 Offset += Size*CI->getSExtValue();
5496 }
5497 } else {
5498 // Found our variable index.
5499 break;
5500 }
5501 }
5502
5503 // If there are no variable indices, we must have a constant offset, just
5504 // evaluate it the general way.
5505 if (i == e) return 0;
5506
5507 Value *VariableIdx = GEP->getOperand(i);
5508 // Determine the scale factor of the variable element. For example, this is
5509 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005510 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005511
5512 // Verify that there are no other variable indices. If so, emit the hard way.
5513 for (++i, ++GTI; i != e; ++i, ++GTI) {
5514 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5515 if (!CI) return 0;
5516
5517 // Compute the aggregate offset of constant indices.
5518 if (CI->isZero()) continue;
5519
5520 // Handle a struct index, which adds its field offset to the pointer.
5521 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5522 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5523 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005524 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005525 Offset += Size*CI->getSExtValue();
5526 }
5527 }
5528
5529 // Okay, we know we have a single variable index, which must be a
5530 // pointer/array/vector index. If there is no offset, life is simple, return
5531 // the index.
5532 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5533 if (Offset == 0) {
5534 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5535 // we don't need to bother extending: the extension won't affect where the
5536 // computation crosses zero.
5537 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5538 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5539 VariableIdx->getNameStart(), &I);
5540 return VariableIdx;
5541 }
5542
5543 // Otherwise, there is an index. The computation we will do will be modulo
5544 // the pointer size, so get it.
5545 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5546
5547 Offset &= PtrSizeMask;
5548 VariableScale &= PtrSizeMask;
5549
5550 // To do this transformation, any constant index must be a multiple of the
5551 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5552 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5553 // multiple of the variable scale.
5554 int64_t NewOffs = Offset / (int64_t)VariableScale;
5555 if (Offset != NewOffs*(int64_t)VariableScale)
5556 return 0;
5557
5558 // Okay, we can do this evaluation. Start by converting the index to intptr.
5559 const Type *IntPtrTy = TD.getIntPtrType();
5560 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005562 true /*SExt*/,
5563 VariableIdx->getNameStart(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005564 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005565 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005566}
5567
5568
Reid Spencere4d87aa2006-12-23 06:05:41 +00005569/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005570/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005571Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5572 ICmpInst::Predicate Cond,
5573 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005574 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005575
Chris Lattner10c0d912008-04-22 02:53:33 +00005576 // Look through bitcasts.
5577 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5578 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005579
Chris Lattner574da9b2005-01-13 20:14:25 +00005580 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005581 if (TD && PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005582 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005583 // This transformation (ignoring the base and scales) is valid because we
5584 // know pointers can't overflow. See if we can output an optimized form.
5585 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5586
5587 // If not, synthesize the offset the hard way.
5588 if (Offset == 0)
5589 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005590 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005591 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005592 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005593 // If the base pointers are different, but the indices are the same, just
5594 // compare the base pointer.
5595 if (PtrBase != GEPRHS->getOperand(0)) {
5596 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005597 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005598 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005599 if (IndicesTheSame)
5600 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5602 IndicesTheSame = false;
5603 break;
5604 }
5605
5606 // If all indices are the same, just compare the base pointers.
5607 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005608 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005609 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005610
5611 // Otherwise, the base pointers are different and the indices are
5612 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005613 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005614 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005615
Chris Lattnere9d782b2005-01-13 22:25:21 +00005616 // If one of the GEPs has all zero indices, recurse.
5617 bool AllZeros = true;
5618 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5619 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5620 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5621 AllZeros = false;
5622 break;
5623 }
5624 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005625 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5626 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005627
5628 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005629 AllZeros = true;
5630 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5631 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5632 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5633 AllZeros = false;
5634 break;
5635 }
5636 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005638
Chris Lattner4401c9c2005-01-14 00:20:05 +00005639 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5640 // If the GEPs only differ by one index, compare it.
5641 unsigned NumDifferences = 0; // Keep track of # differences.
5642 unsigned DiffOperand = 0; // The operand that differs.
5643 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005645 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5646 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005647 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005648 NumDifferences = 2;
5649 break;
5650 } else {
5651 if (NumDifferences++) break;
5652 DiffOperand = i;
5653 }
5654 }
5655
5656 if (NumDifferences == 0) // SAME GEP?
5657 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneed707b2009-07-24 23:12:02 +00005658 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005659 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005660
Chris Lattner4401c9c2005-01-14 00:20:05 +00005661 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005662 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5663 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005665 return new ICmpInst(*Context,
5666 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005667 }
5668 }
5669
Reid Spencere4d87aa2006-12-23 06:05:41 +00005670 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005671 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005672 if (TD &&
5673 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005674 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5675 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5676 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5677 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005678 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005679 }
5680 }
5681 return 0;
5682}
5683
Chris Lattnera5406232008-05-19 20:18:56 +00005684/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5685///
5686Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5687 Instruction *LHSI,
5688 Constant *RHSC) {
5689 if (!isa<ConstantFP>(RHSC)) return 0;
5690 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5691
5692 // Get the width of the mantissa. We don't want to hack on conversions that
5693 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005694 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005695 if (MantissaWidth == -1) return 0; // Unknown.
5696
5697 // Check to see that the input is converted from an integer type that is small
5698 // enough that preserves all bits. TODO: check here for "known" sign bits.
5699 // 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 +00005700 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005701
5702 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5704 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005705 ++InputSize;
5706
5707 // If the conversion would lose info, don't hack on this.
5708 if ((int)InputSize > MantissaWidth)
5709 return 0;
5710
5711 // Otherwise, we can potentially simplify the comparison. We know that it
5712 // will always come through as an integer value and we know the constant is
5713 // not a NAN (it would have been previously simplified).
5714 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5715
5716 ICmpInst::Predicate Pred;
5717 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005718 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005719 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005720 case FCmpInst::FCMP_OEQ:
5721 Pred = ICmpInst::ICMP_EQ;
5722 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005723 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005724 case FCmpInst::FCMP_OGT:
5725 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5726 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005727 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005728 case FCmpInst::FCMP_OGE:
5729 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5730 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005731 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005732 case FCmpInst::FCMP_OLT:
5733 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5734 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005735 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005736 case FCmpInst::FCMP_OLE:
5737 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5738 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005739 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005740 case FCmpInst::FCMP_ONE:
5741 Pred = ICmpInst::ICMP_NE;
5742 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005743 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005744 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005746 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005747 }
5748
5749 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5750
5751 // Now we know that the APFloat is a normal number, zero or inf.
5752
Chris Lattner85162782008-05-20 03:50:52 +00005753 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005754 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005755 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005756
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 if (!LHSUnsigned) {
5758 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5759 // and large values.
5760 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5761 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5762 APFloat::rmNearestTiesToEven);
5763 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5764 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5765 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005766 return ReplaceInstUsesWith(I, Context->getTrue());
5767 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005768 }
5769 } else {
5770 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5771 // +INF and large values.
5772 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5773 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5774 APFloat::rmNearestTiesToEven);
5775 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5776 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5777 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005778 return ReplaceInstUsesWith(I, Context->getTrue());
5779 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005780 }
Chris Lattnera5406232008-05-19 20:18:56 +00005781 }
5782
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005783 if (!LHSUnsigned) {
5784 // See if the RHS value is < SignedMin.
5785 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5786 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5787 APFloat::rmNearestTiesToEven);
5788 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5789 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5790 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005791 return ReplaceInstUsesWith(I, Context->getTrue());
5792 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005793 }
Chris Lattnera5406232008-05-19 20:18:56 +00005794 }
5795
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005796 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5797 // [0, UMAX], but it may still be fractional. See if it is fractional by
5798 // casting the FP value to the integer value and back, checking for equality.
5799 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005800 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005801 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5802 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005803 if (!RHS.isZero()) {
5804 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005805 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5806 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005807 if (!Equal) {
5808 // If we had a comparison against a fractional value, we have to adjust
5809 // the compare predicate and sometimes the value. RHSC is rounded towards
5810 // zero at this point.
5811 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005812 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005813 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005814 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005815 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005816 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 case ICmpInst::ICMP_ULE:
5818 // (float)int <= 4.4 --> int <= 4
5819 // (float)int <= -4.4 --> false
5820 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005821 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005822 break;
5823 case ICmpInst::ICMP_SLE:
5824 // (float)int <= 4.4 --> int <= 4
5825 // (float)int <= -4.4 --> int < -4
5826 if (RHS.isNegative())
5827 Pred = ICmpInst::ICMP_SLT;
5828 break;
5829 case ICmpInst::ICMP_ULT:
5830 // (float)int < -4.4 --> false
5831 // (float)int < 4.4 --> int <= 4
5832 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005833 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005834 Pred = ICmpInst::ICMP_ULE;
5835 break;
5836 case ICmpInst::ICMP_SLT:
5837 // (float)int < -4.4 --> int < -4
5838 // (float)int < 4.4 --> int <= 4
5839 if (!RHS.isNegative())
5840 Pred = ICmpInst::ICMP_SLE;
5841 break;
5842 case ICmpInst::ICMP_UGT:
5843 // (float)int > 4.4 --> int > 4
5844 // (float)int > -4.4 --> true
5845 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005846 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005847 break;
5848 case ICmpInst::ICMP_SGT:
5849 // (float)int > 4.4 --> int > 4
5850 // (float)int > -4.4 --> int >= -4
5851 if (RHS.isNegative())
5852 Pred = ICmpInst::ICMP_SGE;
5853 break;
5854 case ICmpInst::ICMP_UGE:
5855 // (float)int >= -4.4 --> true
5856 // (float)int >= 4.4 --> int > 4
5857 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005858 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005859 Pred = ICmpInst::ICMP_UGT;
5860 break;
5861 case ICmpInst::ICMP_SGE:
5862 // (float)int >= -4.4 --> int >= -4
5863 // (float)int >= 4.4 --> int > 4
5864 if (!RHS.isNegative())
5865 Pred = ICmpInst::ICMP_SGT;
5866 break;
5867 }
Chris Lattnera5406232008-05-19 20:18:56 +00005868 }
5869 }
5870
5871 // Lower this FP comparison into an appropriate integer version of the
5872 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005873 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005874}
5875
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5877 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005878 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005879
Chris Lattner58e97462007-01-14 19:42:17 +00005880 // Fold trivial predicates.
5881 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005882 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005883 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005884 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005885
5886 // Simplify 'fcmp pred X, X'
5887 if (Op0 == Op1) {
5888 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005889 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005890 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5891 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5892 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005893 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005894 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5895 case FCmpInst::FCMP_OLT: // True if ordered and less than
5896 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005897 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005898
5899 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5900 case FCmpInst::FCMP_ULT: // True if unordered or less than
5901 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5902 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5903 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5904 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005905 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005906 return &I;
5907
5908 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5909 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5910 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5911 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5912 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5913 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005914 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005915 return &I;
5916 }
5917 }
5918
Reid Spencere4d87aa2006-12-23 06:05:41 +00005919 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005920 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005921
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 // Handle fcmp with constant RHS
5923 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005924 // If the constant is a nan, see if we can fold the comparison based on it.
5925 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5926 if (CFP->getValueAPF().isNaN()) {
5927 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005928 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005929 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5930 "Comparison must be either ordered or unordered!");
5931 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005932 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005933 }
5934 }
5935
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5937 switch (LHSI->getOpcode()) {
5938 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005939 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5940 // block. If in the same block, we're encouraging jump threading. If
5941 // not, we are just pessimizing the code by making an i1 phi.
5942 if (LHSI->getParent() == I.getParent())
5943 if (Instruction *NV = FoldOpIntoPhi(I))
5944 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005946 case Instruction::SIToFP:
5947 case Instruction::UIToFP:
5948 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5949 return NV;
5950 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005951 case Instruction::Select:
5952 // If either operand of the select is a constant, we can fold the
5953 // comparison into the select arms, which will cause one to be
5954 // constant folded and the select turned into a bitwise or.
5955 Value *Op1 = 0, *Op2 = 0;
5956 if (LHSI->hasOneUse()) {
5957 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5958 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005959 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005961 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 LHSI->getOperand(2), RHSC,
5963 I.getName()), I);
5964 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5965 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005966 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005967 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005968 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 LHSI->getOperand(1), RHSC,
5970 I.getName()), I);
5971 }
5972 }
5973
5974 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005975 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 break;
5977 }
5978 }
5979
5980 return Changed ? &I : 0;
5981}
5982
5983Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5984 bool Changed = SimplifyCompare(I);
5985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5986 const Type *Ty = Op0->getType();
5987
5988 // icmp X, X
5989 if (Op0 == Op1)
Owen Andersoneed707b2009-07-24 23:12:02 +00005990 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005991 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992
5993 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005994 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005995
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005997 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005998 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5999 isa<ConstantPointerNull>(Op0)) &&
6000 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006001 isa<ConstantPointerNull>(Op1)))
Owen Andersoneed707b2009-07-24 23:12:02 +00006002 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006003 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006004
Reid Spencere4d87aa2006-12-23 06:05:41 +00006005 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006006 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006008 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006010 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006011 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006012 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006013 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006015 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006016
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006018 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006019 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006020 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006021 Instruction *Not = BinaryOperator::CreateNot(*Context,
6022 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006023 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006024 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006025 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006026 case ICmpInst::ICMP_SGT:
6027 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006028 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006029 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006030 Instruction *Not = BinaryOperator::CreateNot(*Context,
6031 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006032 InsertNewInstBefore(Not, I);
6033 return BinaryOperator::CreateAnd(Not, Op0);
6034 }
6035 case ICmpInst::ICMP_UGE:
6036 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6037 // FALL THROUGH
6038 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006039 Instruction *Not = BinaryOperator::CreateNot(*Context,
6040 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006041 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006042 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006043 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006044 case ICmpInst::ICMP_SGE:
6045 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6046 // FALL THROUGH
6047 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006048 Instruction *Not = BinaryOperator::CreateNot(*Context,
6049 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006050 InsertNewInstBefore(Not, I);
6051 return BinaryOperator::CreateOr(Not, Op0);
6052 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006053 }
Chris Lattner8b170942002-08-09 23:47:40 +00006054 }
6055
Dan Gohman1c8491e2009-04-25 17:12:48 +00006056 unsigned BitWidth = 0;
6057 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006058 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6059 else if (Ty->isIntOrIntVector())
6060 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006061
6062 bool isSignBit = false;
6063
Dan Gohman81b28ce2008-09-16 18:46:06 +00006064 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006066 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006067
Chris Lattnerb6566012008-01-05 01:18:20 +00006068 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6069 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006070 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006071 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006072 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006073 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006074
Dan Gohman81b28ce2008-09-16 18:46:06 +00006075 // If we have an icmp le or icmp ge instruction, turn it into the
6076 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6077 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006078 switch (I.getPredicate()) {
6079 default: break;
6080 case ICmpInst::ICMP_ULE:
6081 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006082 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6084 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_SLE:
6086 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006087 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006088 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6089 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006090 case ICmpInst::ICMP_UGE:
6091 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006092 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006093 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6094 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006095 case ICmpInst::ICMP_SGE:
6096 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006097 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006098 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6099 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006100 }
6101
Chris Lattner183661e2008-07-11 05:40:05 +00006102 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006103 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006104 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6106 }
6107
6108 // See if we can fold the comparison based on range information we can get
6109 // by checking whether bits are known to be zero or one in the input.
6110 if (BitWidth != 0) {
6111 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6112 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6113
6114 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006115 isSignBit ? APInt::getSignBit(BitWidth)
6116 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006118 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (SimplifyDemandedBits(I.getOperandUse(1),
6120 APInt::getAllOnesValue(BitWidth),
6121 Op1KnownZero, Op1KnownOne, 0))
6122 return &I;
6123
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006124 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006125 // in. Compute the Min, Max and RHS values based on the known bits. For the
6126 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6128 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6129 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6130 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131 Op0Min, Op0Max);
6132 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133 Op1Min, Op1Max);
6134 } else {
6135 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6136 Op0Min, Op0Max);
6137 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6138 Op1Min, Op1Max);
6139 }
6140
Chris Lattner183661e2008-07-11 05:40:05 +00006141 // If Min and Max are known to be the same, then SimplifyDemandedBits
6142 // figured out that the LHS is a constant. Just constant fold this now so
6143 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006145 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006146 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006148 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006149 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150
Chris Lattner183661e2008-07-11 05:40:05 +00006151 // Based on the range information we know about the LHS, see if we can
6152 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006154 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006155 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006156 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006157 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006158 break;
6159 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006160 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006161 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006162 break;
6163 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006165 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006167 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006169 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6171 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6173 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174
6175 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6176 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006177 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006178 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 }
Chris Lattner84dff672008-07-11 05:08:55 +00006180 break;
6181 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006183 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006185 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186
6187 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006188 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6190 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6192 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193
6194 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6195 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006196 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006197 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 }
Chris Lattner84dff672008-07-11 05:08:55 +00006199 break;
6200 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006202 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006204 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006206 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6208 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006209 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6210 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 }
Chris Lattner84dff672008-07-11 05:08:55 +00006212 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 case ICmpInst::ICMP_SGT:
6214 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006215 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006217 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218
6219 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006220 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6222 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006223 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6224 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 }
6226 break;
6227 case ICmpInst::ICMP_SGE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6229 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006230 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006232 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 break;
6234 case ICmpInst::ICMP_SLE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6236 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006237 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006239 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 break;
6241 case ICmpInst::ICMP_UGE:
6242 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6243 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006244 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006246 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006247 break;
6248 case ICmpInst::ICMP_ULE:
6249 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6250 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006251 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006252 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006253 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006254 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006255 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006256
6257 // Turn a signed comparison into an unsigned one if both operands
6258 // are known to have the same sign.
6259 if (I.isSignedPredicate() &&
6260 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6261 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006262 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006263 }
6264
6265 // Test if the ICmpInst instruction is used exclusively by a select as
6266 // part of a minimum or maximum operation. If so, refrain from doing
6267 // any other folding. This helps out other analyses which understand
6268 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6269 // and CodeGen. And in this case, at least one of the comparison
6270 // operands has at least one user besides the compare (the select),
6271 // which would often largely negate the benefit of folding anyway.
6272 if (I.hasOneUse())
6273 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6274 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6275 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6276 return 0;
6277
6278 // See if we are doing a comparison between a constant and an instruction that
6279 // can be folded into the comparison.
6280 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006282 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006283 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006284 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006285 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6286 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006287 }
6288
Chris Lattner01deb9d2007-04-03 17:43:25 +00006289 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006290 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6291 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6292 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006293 case Instruction::GetElementPtr:
6294 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006296 bool isAllZeros = true;
6297 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6298 if (!isa<Constant>(LHSI->getOperand(i)) ||
6299 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6300 isAllZeros = false;
6301 break;
6302 }
6303 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006304 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006305 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006306 }
6307 break;
6308
Chris Lattner6970b662005-04-23 15:31:55 +00006309 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006310 // Only fold icmp into the PHI if the phi and fcmp are in the same
6311 // block. If in the same block, we're encouraging jump threading. If
6312 // not, we are just pessimizing the code by making an i1 phi.
6313 if (LHSI->getParent() == I.getParent())
6314 if (Instruction *NV = FoldOpIntoPhi(I))
6315 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006316 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006317 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006318 // If either operand of the select is a constant, we can fold the
6319 // comparison into the select arms, which will cause one to be
6320 // constant folded and the select turned into a bitwise or.
6321 Value *Op1 = 0, *Op2 = 0;
6322 if (LHSI->hasOneUse()) {
6323 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6324 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006325 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006327 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 LHSI->getOperand(2), RHSC,
6329 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006330 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6331 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006332 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006334 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 LHSI->getOperand(1), RHSC,
6336 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006337 }
6338 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006339
Chris Lattner6970b662005-04-23 15:31:55 +00006340 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006341 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006342 break;
6343 }
Chris Lattner4802d902007-04-06 18:57:34 +00006344 case Instruction::Malloc:
6345 // If we have (malloc != null), and if the malloc has a single use, we
6346 // can assume it is successful and remove the malloc.
6347 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6348 AddToWorkList(LHSI);
Owen Andersoneed707b2009-07-24 23:12:02 +00006349 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006350 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006351 }
6352 break;
6353 }
Chris Lattner6970b662005-04-23 15:31:55 +00006354 }
6355
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006357 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006358 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006359 return NI;
6360 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006361 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6362 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006363 return NI;
6364
Reid Spencere4d87aa2006-12-23 06:05:41 +00006365 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006366 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6367 // now.
6368 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6369 if (isa<PointerType>(Op0->getType()) &&
6370 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006371 // We keep moving the cast from the left operand over to the right
6372 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006373 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006374
Chris Lattner57d86372007-01-06 01:45:59 +00006375 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6376 // so eliminate it as well.
6377 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6378 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006379
Chris Lattnerde90b762003-11-03 04:25:02 +00006380 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006381 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006382 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006383 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006384 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006385 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006386 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006387 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006388 }
Owen Anderson333c4002009-07-09 23:48:35 +00006389 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006390 }
Chris Lattner57d86372007-01-06 01:45:59 +00006391 }
6392
6393 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006395 // This comes up when you have code like
6396 // int X = A < B;
6397 // if (X) ...
6398 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006399 // with a constant or another cast from the same type.
6400 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006401 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006402 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006403 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006404
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006405 // See if it's the same type of instruction on the left and right.
6406 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6407 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006408 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006409 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006410 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006411 default: break;
6412 case Instruction::Add:
6413 case Instruction::Sub:
6414 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006415 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006416 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006417 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006418 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6419 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6420 if (CI->getValue().isSignBit()) {
6421 ICmpInst::Predicate Pred = I.isSignedPredicate()
6422 ? I.getUnsignedPredicate()
6423 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006424 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006425 Op1I->getOperand(0));
6426 }
6427
6428 if (CI->getValue().isMaxSignedValue()) {
6429 ICmpInst::Predicate Pred = I.isSignedPredicate()
6430 ? I.getUnsignedPredicate()
6431 : I.getSignedPredicate();
6432 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006433 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006434 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006435 }
6436 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006437 break;
6438 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006439 if (!I.isEquality())
6440 break;
6441
Nick Lewycky5d52c452008-08-21 05:56:10 +00006442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6443 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6444 // Mask = -1 >> count-trailing-zeros(Cst).
6445 if (!CI->isZero() && !CI->isOne()) {
6446 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006447 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006448 APInt::getLowBitsSet(AP.getBitWidth(),
6449 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006450 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006451 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6452 Mask);
6453 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6454 Mask);
6455 InsertNewInstBefore(And1, I);
6456 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006457 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006458 }
6459 }
6460 break;
6461 }
6462 }
6463 }
6464 }
6465
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006466 // ~x < ~y --> y < x
6467 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006468 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6469 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006470 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006471 }
6472
Chris Lattner65b72ba2006-09-18 04:22:48 +00006473 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006474 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006475
6476 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006477 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6478 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006479 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006480
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006481 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6483 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006484 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006485 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006486 }
6487
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006488 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006489 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006490 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006491 if (match(B, m_ConstantInt(C1), *Context) &&
6492 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006493 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006494 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006495 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006496 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006497 InsertNewInstBefore(Xor, I));
6498 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006499
6500 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006501 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6502 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6503 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6504 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006505 }
6506 }
6507
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006508 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006509 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006510 // A == (A^B) -> B == 0
6511 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006512 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006513 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006514 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006515
6516 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006517 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006518 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006519 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006520
6521 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006522 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006523 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006524 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006525
Chris Lattner9c2328e2006-11-14 06:06:06 +00006526 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6527 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006528 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6529 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006530 Value *X = 0, *Y = 0, *Z = 0;
6531
6532 if (A == C) {
6533 X = B; Y = D; Z = A;
6534 } else if (A == D) {
6535 X = B; Y = C; Z = A;
6536 } else if (B == C) {
6537 X = A; Y = D; Z = B;
6538 } else if (B == D) {
6539 X = A; Y = C; Z = B;
6540 }
6541
6542 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006543 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6544 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006545 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006546 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006547 return &I;
6548 }
6549 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006550 }
Chris Lattner7e708292002-06-25 16:13:24 +00006551 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006552}
6553
Chris Lattner562ef782007-06-20 23:46:26 +00006554
6555/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6556/// and CmpRHS are both known to be integer constants.
6557Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6558 ConstantInt *DivRHS) {
6559 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6560 const APInt &CmpRHSV = CmpRHS->getValue();
6561
6562 // FIXME: If the operand types don't match the type of the divide
6563 // then don't attempt this transform. The code below doesn't have the
6564 // logic to deal with a signed divide and an unsigned compare (and
6565 // vice versa). This is because (x /s C1) <s C2 produces different
6566 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6567 // (x /u C1) <u C2. Simply casting the operands and result won't
6568 // work. :( The if statement below tests that condition and bails
6569 // if it finds it.
6570 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6571 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6572 return 0;
6573 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006575 if (DivIsSigned && DivRHS->isAllOnesValue())
6576 return 0; // The overflow computation also screws up here
6577 if (DivRHS->isOne())
6578 return 0; // Not worth bothering, and eliminates some funny cases
6579 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006580
6581 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6582 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6583 // C2 (CI). By solving for X we can turn this into a range check
6584 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006585 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006586
6587 // Determine if the product overflows by seeing if the product is
6588 // not equal to the divide. Make sure we do the same kind of divide
6589 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006590 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6591 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006592
6593 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006595
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 // Figure out the interval that is being checked. For example, a comparison
6597 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6598 // Compute this interval based on the constants involved and the signedness of
6599 // the compare/divide. This computes a half-open interval, keeping track of
6600 // whether either value in the interval overflows. After analysis each
6601 // overflow variable is set to 0 if it's corresponding bound variable is valid
6602 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6603 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006604 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605
Chris Lattner562ef782007-06-20 23:46:26 +00006606 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006608 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 HiOverflow = LoOverflow = ProdOV;
6610 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006611 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006612 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006613 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006614 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006615 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6616 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006617 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006618 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6620 HiOverflow = LoOverflow = ProdOV;
6621 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006622 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006623 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006625 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006626 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6627 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006628 ConstantInt* DivNeg =
6629 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6630 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006631 true) ? -1 : 0;
6632 }
Chris Lattner562ef782007-06-20 23:46:26 +00006633 }
Dan Gohman76491272008-02-13 22:09:18 +00006634 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006635 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006636 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006637 LoBound = AddOne(DivRHS, Context);
6638 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6640 HiOverflow = 1; // [INTMIN+1, overflow)
6641 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6642 }
Dan Gohman76491272008-02-13 22:09:18 +00006643 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006644 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006645 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006647 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006648 LoOverflow = AddWithOverflow(LoBound, HiBound,
6649 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006650 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006651 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6652 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006653 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006654 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006655 }
6656
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 // Dividing by a negative swaps the condition. LT <-> GT
6658 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006659 }
6660
6661 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006663 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006664 case ICmpInst::ICMP_EQ:
6665 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006666 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006667 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006668 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006669 ICmpInst::ICMP_UGE, X, LoBound);
6670 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006671 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006672 ICmpInst::ICMP_ULT, X, HiBound);
6673 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006674 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006675 case ICmpInst::ICMP_NE:
6676 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006677 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006678 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006679 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006680 ICmpInst::ICMP_ULT, X, LoBound);
6681 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006682 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006683 ICmpInst::ICMP_UGE, X, HiBound);
6684 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006686 case ICmpInst::ICMP_ULT:
6687 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006688 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006689 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006691 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006692 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006693 case ICmpInst::ICMP_UGT:
6694 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006696 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006697 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006698 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006699 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006700 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006701 else
Owen Anderson333c4002009-07-09 23:48:35 +00006702 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006703 }
6704}
6705
6706
Chris Lattner01deb9d2007-04-03 17:43:25 +00006707/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6708///
6709Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6710 Instruction *LHSI,
6711 ConstantInt *RHS) {
6712 const APInt &RHSV = RHS->getValue();
6713
6714 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006715 case Instruction::Trunc:
6716 if (ICI.isEquality() && LHSI->hasOneUse()) {
6717 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6718 // of the high bits truncated out of x are known.
6719 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6720 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6721 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6722 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6723 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6724
6725 // If all the high bits are known, we can do this xform.
6726 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6727 // Pull in the high bits from known-ones set.
6728 APInt NewRHS(RHS->getValue());
6729 NewRHS.zext(SrcBits);
6730 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006731 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006732 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006733 }
6734 }
6735 break;
6736
Duncan Sands0091bf22007-04-04 06:42:45 +00006737 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006738 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6739 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6740 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006741 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6742 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006743 Value *CompareVal = LHSI->getOperand(0);
6744
6745 // If the sign bit of the XorCST is not set, there is no change to
6746 // the operation, just stop using the Xor.
6747 if (!XorCST->getValue().isNegative()) {
6748 ICI.setOperand(0, CompareVal);
6749 AddToWorkList(LHSI);
6750 return &ICI;
6751 }
6752
6753 // Was the old condition true if the operand is positive?
6754 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6755
6756 // If so, the new one isn't.
6757 isTrueIfPositive ^= true;
6758
6759 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006760 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006761 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006762 else
Owen Anderson333c4002009-07-09 23:48:35 +00006763 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006764 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006765 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006766
6767 if (LHSI->hasOneUse()) {
6768 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6769 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6770 const APInt &SignBit = XorCST->getValue();
6771 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6772 ? ICI.getUnsignedPredicate()
6773 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006774 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006775 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006776 }
6777
6778 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006779 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006780 const APInt &NotSignBit = XorCST->getValue();
6781 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6782 ? ICI.getUnsignedPredicate()
6783 : ICI.getSignedPredicate();
6784 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006785 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006786 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006787 }
6788 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 }
6790 break;
6791 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6792 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6793 LHSI->getOperand(0)->hasOneUse()) {
6794 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6795
6796 // If the LHS is an AND of a truncating cast, we can widen the
6797 // and/compare to be the input width without changing the value
6798 // produced, eliminating a cast.
6799 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6800 // We can do this transformation if either the AND constant does not
6801 // have its sign bit set or if it is an equality comparison.
6802 // Extending a relational comparison when we're checking the sign
6803 // bit would not work.
6804 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006805 (ICI.isEquality() ||
6806 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006807 uint32_t BitWidth =
6808 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6809 APInt NewCST = AndCST->getValue();
6810 NewCST.zext(BitWidth);
6811 APInt NewCI = RHSV;
6812 NewCI.zext(BitWidth);
6813 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006814 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006815 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006817 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006818 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 }
6820 }
6821
6822 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6823 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6824 // happens a LOT in code produced by the C front-end, for bitfield
6825 // access.
6826 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6827 if (Shift && !Shift->isShift())
6828 Shift = 0;
6829
6830 ConstantInt *ShAmt;
6831 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6832 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6833 const Type *AndTy = AndCST->getType(); // Type of the and.
6834
6835 // We can fold this as long as we can't shift unknown bits
6836 // into the mask. This can only happen with signed shift
6837 // rights, as they sign-extend.
6838 if (ShAmt) {
6839 bool CanFold = Shift->isLogicalShift();
6840 if (!CanFold) {
6841 // To test for the bad case of the signed shr, see if any
6842 // of the bits shifted in could be tested after the mask.
6843 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6844 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6845
6846 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6847 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6848 AndCST->getValue()) == 0)
6849 CanFold = true;
6850 }
6851
6852 if (CanFold) {
6853 Constant *NewCst;
6854 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006855 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006856 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006857 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858
6859 // Check to see if we are shifting out any of the bits being
6860 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006861 if (Context->getConstantExpr(Shift->getOpcode(),
6862 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 // If we shifted bits out, the fold is not going to work out.
6864 // As a special case, check to see if this means that the
6865 // result is always true or false now.
6866 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006867 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006868 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006869 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 } else {
6871 ICI.setOperand(1, NewCst);
6872 Constant *NewAndCST;
6873 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006874 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006876 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 LHSI->setOperand(1, NewAndCST);
6878 LHSI->setOperand(0, Shift->getOperand(0));
6879 AddToWorkList(Shift); // Shift is dead.
6880 AddUsesToWorkList(ICI);
6881 return &ICI;
6882 }
6883 }
6884 }
6885
6886 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6887 // preferable because it allows the C<<Y expression to be hoisted out
6888 // of a loop if Y is invariant and X is not.
6889 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006890 ICI.isEquality() && !Shift->isArithmeticShift() &&
6891 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006892 // Compute C << Y.
6893 Value *NS;
6894 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006895 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006896 Shift->getOperand(1), "tmp");
6897 } else {
6898 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006899 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006900 Shift->getOperand(1), "tmp");
6901 }
6902 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6903
6904 // Compute X & (C << Y).
6905 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006906 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 InsertNewInstBefore(NewAnd, ICI);
6908
6909 ICI.setOperand(0, NewAnd);
6910 return &ICI;
6911 }
6912 }
6913 break;
6914
Chris Lattnera0141b92007-07-15 20:42:37 +00006915 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6916 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6917 if (!ShAmt) break;
6918
6919 uint32_t TypeBits = RHSV.getBitWidth();
6920
6921 // Check that the shift amount is in range. If not, don't perform
6922 // undefined shifts. When the shift is visited it will be
6923 // simplified.
6924 if (ShAmt->uge(TypeBits))
6925 break;
6926
6927 if (ICI.isEquality()) {
6928 // If we are comparing against bits always shifted out, the
6929 // comparison cannot succeed.
6930 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006931 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6932 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006933 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6934 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006935 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006936 return ReplaceInstUsesWith(ICI, Cst);
6937 }
6938
6939 if (LHSI->hasOneUse()) {
6940 // Otherwise strength reduce the shift into an and.
6941 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6942 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006943 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006944 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945
Chris Lattnera0141b92007-07-15 20:42:37 +00006946 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006947 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006948 Mask, LHSI->getName()+".mask");
6949 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006950 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006951 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006952 }
6953 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006954
6955 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6956 bool TrueIfSigned = false;
6957 if (LHSI->hasOneUse() &&
6958 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6959 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006960 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006961 (TypeBits-ShAmt->getZExtValue()-1));
6962 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006963 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006964 Mask, LHSI->getName()+".mask");
6965 Value *And = InsertNewInstBefore(AndI, ICI);
6966
Owen Anderson333c4002009-07-09 23:48:35 +00006967 return new ICmpInst(*Context,
6968 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006969 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006972 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006973
6974 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006975 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006976 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006977 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006978 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006979
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006980 // Check that the shift amount is in range. If not, don't perform
6981 // undefined shifts. When the shift is visited it will be
6982 // simplified.
6983 uint32_t TypeBits = RHSV.getBitWidth();
6984 if (ShAmt->uge(TypeBits))
6985 break;
6986
6987 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006988
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006989 // If we are comparing against bits always shifted out, the
6990 // comparison cannot succeed.
6991 APInt Comp = RHSV << ShAmtVal;
6992 if (LHSI->getOpcode() == Instruction::LShr)
6993 Comp = Comp.lshr(ShAmtVal);
6994 else
6995 Comp = Comp.ashr(ShAmtVal);
6996
6997 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6998 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneed707b2009-07-24 23:12:02 +00006999 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007000 return ReplaceInstUsesWith(ICI, Cst);
7001 }
7002
7003 // Otherwise, check to see if the bits shifted out are known to be zero.
7004 // If so, we can compare against the unshifted value:
7005 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007006 if (LHSI->hasOneUse() &&
7007 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007008 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007009 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007010 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007011 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007012
Evan Chengf30752c2008-04-23 00:38:06 +00007013 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007014 // Otherwise strength reduce the shift into an and.
7015 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007016 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007017
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007018 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007019 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007020 Mask, LHSI->getName()+".mask");
7021 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007022 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007023 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007024 }
7025 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007026 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007027
7028 case Instruction::SDiv:
7029 case Instruction::UDiv:
7030 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7031 // Fold this div into the comparison, producing a range check.
7032 // Determine, based on the divide type, what the range is being
7033 // checked. If there is an overflow on the low or high side, remember
7034 // it, otherwise compute the range [low, hi) bounding the new value.
7035 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007036 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7037 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7038 DivRHS))
7039 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007040 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007041
7042 case Instruction::Add:
7043 // Fold: icmp pred (add, X, C1), C2
7044
7045 if (!ICI.isEquality()) {
7046 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7047 if (!LHSC) break;
7048 const APInt &LHSV = LHSC->getValue();
7049
7050 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7051 .subtract(LHSV);
7052
7053 if (ICI.isSignedPredicate()) {
7054 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007055 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007056 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007057 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007059 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007060 }
7061 } else {
7062 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007063 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007064 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007065 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007066 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007067 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007068 }
7069 }
7070 }
7071 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007072 }
7073
7074 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7075 if (ICI.isEquality()) {
7076 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7077
7078 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7079 // the second operand is a constant, simplify a bit.
7080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7081 switch (BO->getOpcode()) {
7082 case Instruction::SRem:
7083 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7084 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7085 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7086 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7087 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007088 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007089 BO->getName());
7090 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007091 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007092 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007093 }
7094 }
7095 break;
7096 case Instruction::Add:
7097 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7098 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7099 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007100 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007101 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007102 } else if (RHSV == 0) {
7103 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7104 // efficiently invertible, or if the add has just this one use.
7105 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7106
Owen Andersond672ecb2009-07-03 00:17:18 +00007107 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007108 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007109 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007110 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007112 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007113 InsertNewInstBefore(Neg, ICI);
7114 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007115 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116 }
7117 }
7118 break;
7119 case Instruction::Xor:
7120 // For the xor case, we can xor two constants together, eliminating
7121 // the explicit xor.
7122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007123 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007124 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125
7126 // FALLTHROUGH
7127 case Instruction::Sub:
7128 // Replace (([sub|xor] A, B) != 0) with (A != B)
7129 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007130 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007131 BO->getOperand(1));
7132 break;
7133
7134 case Instruction::Or:
7135 // If bits are being or'd in that are not present in the constant we
7136 // are comparing against, then the comparison could never succeed!
7137 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007138 Constant *NotCI = Context->getConstantExprNot(RHS);
7139 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7140 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007141 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007142 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007143 }
7144 break;
7145
7146 case Instruction::And:
7147 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7148 // If bits are being compared against that are and'd out, then the
7149 // comparison can never succeed!
7150 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007151 return ReplaceInstUsesWith(ICI,
Owen Andersoneed707b2009-07-24 23:12:02 +00007152 ConstantInt::get(Type::Int1Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007153 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154
7155 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7156 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007157 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007159 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160
7161 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007162 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007163 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007164 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007165 ICmpInst::Predicate pred = isICMP_NE ?
7166 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007167 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007168 }
7169
7170 // ((X & ~7) == 0) --> X < 8
7171 if (RHSV == 0 && isHighOnes(BOC)) {
7172 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007173 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 ICmpInst::Predicate pred = isICMP_NE ?
7175 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007176 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007177 }
7178 }
7179 default: break;
7180 }
7181 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7182 // Handle icmp {eq|ne} <intrinsic>, intcst.
7183 if (II->getIntrinsicID() == Intrinsic::bswap) {
7184 AddToWorkList(II);
7185 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007186 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007187 return &ICI;
7188 }
7189 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007190 }
7191 return 0;
7192}
7193
7194/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7195/// We only handle extending casts so far.
7196///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7198 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007199 Value *LHSCIOp = LHSCI->getOperand(0);
7200 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007201 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007202 Value *RHSCIOp;
7203
Chris Lattner8c756c12007-05-05 22:41:33 +00007204 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7205 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007206 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7207 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007208 cast<IntegerType>(DestTy)->getBitWidth()) {
7209 Value *RHSOp = 0;
7210 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007211 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007212 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7213 RHSOp = RHSC->getOperand(0);
7214 // If the pointer types don't match, insert a bitcast.
7215 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007216 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007217 }
7218
7219 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007220 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007221 }
7222
7223 // The code below only handles extension cast instructions, so far.
7224 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 if (LHSCI->getOpcode() != Instruction::ZExt &&
7226 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007227 return 0;
7228
Reid Spencere4d87aa2006-12-23 06:05:41 +00007229 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7230 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007231
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007233 // Not an extension from the same type?
7234 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 if (RHSCIOp->getType() != LHSCIOp->getType())
7236 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007237
Nick Lewycky4189a532008-01-28 03:48:02 +00007238 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007239 // and the other is a zext), then we can't handle this.
7240 if (CI->getOpcode() != LHSCI->getOpcode())
7241 return 0;
7242
Nick Lewycky4189a532008-01-28 03:48:02 +00007243 // Deal with equality cases early.
7244 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007246
7247 // A signed comparison of sign extended values simplifies into a
7248 // signed comparison.
7249 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007250 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007251
7252 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007253 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007254 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007255
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 // If we aren't dealing with a constant on the RHS, exit early
7257 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7258 if (!CI)
7259 return 0;
7260
7261 // Compute the constant that would happen if we truncated to SrcTy then
7262 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007263 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7264 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7265 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266
7267 // If the re-extended constant didn't change...
7268 if (Res2 == CI) {
7269 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7270 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007271 // %A = sext i16 %X to i32
7272 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007273 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007274 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 // because %A may have negative value.
7276 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007277 // However, we allow this when the compare is EQ/NE, because they are
7278 // signless.
7279 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007280 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007281 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007282 }
7283
7284 // The re-extended constant changed so the constant cannot be represented
7285 // in the shorter type. Consequently, we cannot emit a simple comparison.
7286
7287 // First, handle some easy cases. We know the result cannot be equal at this
7288 // point so handle the ICI.isEquality() cases
7289 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007290 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007292 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007293
7294 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7295 // should have been folded away previously and not enter in here.
7296 Value *Result;
7297 if (isSignedCmp) {
7298 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007299 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007300 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007301 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007302 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007303 } else {
7304 // We're performing an unsigned comparison.
7305 if (isSignedExt) {
7306 // We're performing an unsigned comp with a sign extended value.
7307 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007308 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007309 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7310 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007311 } else {
7312 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007313 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007314 }
7315 }
7316
7317 // Finally, return the value computed.
7318 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007319 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007320 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007321
7322 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7323 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7324 "ICmp should be folded!");
7325 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007326 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007327 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007328}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007329
Reid Spencer832254e2007-02-02 02:16:23 +00007330Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7331 return commonShiftTransforms(I);
7332}
7333
7334Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7335 return commonShiftTransforms(I);
7336}
7337
7338Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007339 if (Instruction *R = commonShiftTransforms(I))
7340 return R;
7341
7342 Value *Op0 = I.getOperand(0);
7343
7344 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7345 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7346 if (CSI->isAllOnesValue())
7347 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007348
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007349 // See if we can turn a signed shr into an unsigned shr.
7350 if (MaskedValueIsZero(Op0,
7351 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7352 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7353
7354 // Arithmetic shifting an all-sign-bit value is a no-op.
7355 unsigned NumSignBits = ComputeNumSignBits(Op0);
7356 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7357 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007358
Chris Lattner348f6652007-12-06 01:59:46 +00007359 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007360}
7361
7362Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7363 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007364 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007365
7366 // shl X, 0 == X and shr X, 0 == X
7367 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007368 if (Op1 == Context->getNullValue(Op1->getType()) ||
7369 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007370 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007371
Reid Spencere4d87aa2006-12-23 06:05:41 +00007372 if (isa<UndefValue>(Op0)) {
7373 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007374 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007375 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007376 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007377 }
7378 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007379 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7380 return ReplaceInstUsesWith(I, Op0);
7381 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007382 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007383 }
7384
Dan Gohman9004c8a2009-05-21 02:28:33 +00007385 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007386 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007387 return &I;
7388
Chris Lattner2eefe512004-04-09 19:05:30 +00007389 // Try to fold constant and into select arguments.
7390 if (isa<Constant>(Op0))
7391 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007392 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007393 return R;
7394
Reid Spencerb83eb642006-10-20 07:07:24 +00007395 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007396 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7397 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007398 return 0;
7399}
7400
Reid Spencerb83eb642006-10-20 07:07:24 +00007401Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007402 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007403 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007405 // See if we can simplify any instructions used by the instruction whose sole
7406 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007407 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007408
Dan Gohmana119de82009-06-14 23:30:43 +00007409 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7410 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007412 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007413 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007414 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007415 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007416 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007417 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007418 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007419 }
7420
7421 // ((X*C1) << C2) == (X * (C1 << C2))
7422 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7423 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7424 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007425 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007426 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007427
7428 // Try to fold constant and into select arguments.
7429 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7430 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7431 return R;
7432 if (isa<PHINode>(Op0))
7433 if (Instruction *NV = FoldOpIntoPhi(I))
7434 return NV;
7435
Chris Lattner8999dd32007-12-22 09:07:47 +00007436 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7437 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7438 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7439 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7440 // place. Don't try to do this transformation in this case. Also, we
7441 // require that the input operand is a shift-by-constant so that we have
7442 // confidence that the shifts will get folded together. We could do this
7443 // xform in more cases, but it is unlikely to be profitable.
7444 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7445 isa<ConstantInt>(TrOp->getOperand(1))) {
7446 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007447 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007448 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007449 I.getName());
7450 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7451
7452 // For logical shifts, the truncation has the effect of making the high
7453 // part of the register be zeros. Emulate this by inserting an AND to
7454 // clear the top bits as needed. This 'and' will usually be zapped by
7455 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007456 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7457 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007458 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7459
7460 // The mask we constructed says what the trunc would do if occurring
7461 // between the shifts. We want to know the effect *after* the second
7462 // shift. We know that it is a logical shift by a constant, so adjust the
7463 // mask as appropriate.
7464 if (I.getOpcode() == Instruction::Shl)
7465 MaskV <<= Op1->getZExtValue();
7466 else {
7467 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7468 MaskV = MaskV.lshr(Op1->getZExtValue());
7469 }
7470
Owen Andersond672ecb2009-07-03 00:17:18 +00007471 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007472 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007473 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007474 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7475
7476 // Return the value truncated to the interesting size.
7477 return new TruncInst(And, I.getType());
7478 }
7479 }
7480
Chris Lattner4d5542c2006-01-06 07:12:35 +00007481 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007482 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7483 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7484 Value *V1, *V2;
7485 ConstantInt *CC;
7486 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007487 default: break;
7488 case Instruction::Add:
7489 case Instruction::And:
7490 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007491 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007492 // These operators commute.
7493 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007495 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7496 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007497 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007498 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 Op0BO->getName());
7500 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007501 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007502 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007503 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007504 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007505 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007506 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007507 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007508 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007509
Chris Lattner150f12a2005-09-18 06:30:59 +00007510 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007511 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007512 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007513 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007514 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007515 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007516 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007517 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007518 Op0BO->getOperand(0), Op1,
7519 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007520 InsertNewInstBefore(YS, I); // (Y << C)
7521 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007522 BinaryOperator::CreateAnd(V1,
7523 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007524 V1->getName()+".mask");
7525 InsertNewInstBefore(XM, I); // X & (CC << C)
7526
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007528 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007529 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007530
Reid Spencera07cb7d2007-02-02 14:41:37 +00007531 // FALL THROUGH.
7532 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007533 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007534 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007535 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7536 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007537 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007538 Op0BO->getOperand(1), Op1,
7539 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007540 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007541 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007542 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007543 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007545 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007546 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007547 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007548 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007549
Chris Lattner13d4ab42006-05-31 21:14:00 +00007550 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007551 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7552 match(Op0BO->getOperand(0),
7553 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007554 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007555 cast<BinaryOperator>(Op0BO->getOperand(0))
7556 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007557 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007558 Op0BO->getOperand(1), Op1,
7559 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007560 InsertNewInstBefore(YS, I); // (Y << C)
7561 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007562 BinaryOperator::CreateAnd(V1,
7563 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007564 V1->getName()+".mask");
7565 InsertNewInstBefore(XM, I); // X & (CC << C)
7566
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007567 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007568 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007569
Chris Lattner11021cb2005-09-18 05:12:10 +00007570 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007571 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007572 }
7573
7574
7575 // If the operand is an bitwise operator with a constant RHS, and the
7576 // shift is the only use, we can pull it out of the shift.
7577 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7578 bool isValid = true; // Valid only for And, Or, Xor
7579 bool highBitSet = false; // Transform if high bit of constant set?
7580
7581 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007582 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007583 case Instruction::Add:
7584 isValid = isLeftShift;
7585 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007586 case Instruction::Or:
7587 case Instruction::Xor:
7588 highBitSet = false;
7589 break;
7590 case Instruction::And:
7591 highBitSet = true;
7592 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007593 }
7594
7595 // If this is a signed shift right, and the high bit is modified
7596 // by the logical operation, do not perform the transformation.
7597 // The highBitSet boolean indicates the value of the high bit of
7598 // the constant which would cause it to be modified for this
7599 // operation.
7600 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007601 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007602 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007603
7604 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007605 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606
7607 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007608 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007610 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007611
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007612 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007613 NewRHS);
7614 }
7615 }
7616 }
7617 }
7618
Chris Lattnerad0124c2006-01-06 07:52:12 +00007619 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007620 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7621 if (ShiftOp && !ShiftOp->isShift())
7622 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007623
Reid Spencerb83eb642006-10-20 07:07:24 +00007624 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007625 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007626 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7627 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7629 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7630 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007631
Zhou Sheng4351c642007-04-02 08:20:41 +00007632 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633
7634 const IntegerType *Ty = cast<IntegerType>(I.getType());
7635
7636 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007637 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007638 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7639 // saturates.
7640 if (AmtSum >= TypeBits) {
7641 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007642 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007643 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7644 }
7645
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007646 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007647 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7649 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007650 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007651 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007652
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007655 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7656 I.getOpcode() == Instruction::LShr) {
7657 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007658 if (AmtSum >= TypeBits)
7659 AmtSum = TypeBits-1;
7660
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007662 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007663 InsertNewInstBefore(Shift, I);
7664
Zhou Shenge9e03f62007-03-28 15:02:20 +00007665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007666 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007667 }
7668
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669 // Okay, if we get here, one shift must be left, and the other shift must be
7670 // right. See if the amounts are equal.
7671 if (ShiftAmt1 == ShiftAmt2) {
7672 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7673 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007674 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007675 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 }
7677 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7678 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007680 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007681 }
7682 // We can simplify ((X << C) >>s C) into a trunc + sext.
7683 // NOTE: we could do this for any C, but that would make 'unusual' integer
7684 // types. For now, just stick to ones well-supported by the code
7685 // generators.
7686 const Type *SExtType = 0;
7687 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007688 case 1 :
7689 case 8 :
7690 case 16 :
7691 case 32 :
7692 case 64 :
7693 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007694 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007695 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007696 default: break;
7697 }
7698 if (SExtType) {
7699 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7700 InsertNewInstBefore(NewTrunc, I);
7701 return new SExtInst(NewTrunc, Ty);
7702 }
7703 // Otherwise, we can't handle it yet.
7704 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007705 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007706
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007707 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708 if (I.getOpcode() == Instruction::Shl) {
7709 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7710 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007711 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007712 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007713 InsertNewInstBefore(Shift, I);
7714
Reid Spencer55702aa2007-03-25 21:11:44 +00007715 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007716 return BinaryOperator::CreateAnd(Shift,
7717 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007718 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007720 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 if (I.getOpcode() == Instruction::LShr) {
7722 assert(ShiftOp->getOpcode() == Instruction::Shl);
7723 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007724 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007725 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007726
Reid Spencerd5e30f02007-03-26 17:18:58 +00007727 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007728 return BinaryOperator::CreateAnd(Shift,
7729 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007730 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731
7732 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7733 } else {
7734 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007735 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007736
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007737 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007738 if (I.getOpcode() == Instruction::Shl) {
7739 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7740 ShiftOp->getOpcode() == Instruction::AShr);
7741 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007742 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007743 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 InsertNewInstBefore(Shift, I);
7745
Reid Spencer55702aa2007-03-25 21:11:44 +00007746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007747 return BinaryOperator::CreateAnd(Shift,
7748 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007749 }
7750
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007751 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007752 if (I.getOpcode() == Instruction::LShr) {
7753 assert(ShiftOp->getOpcode() == Instruction::Shl);
7754 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007755 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007756 InsertNewInstBefore(Shift, I);
7757
Reid Spencer68d27cf2007-03-26 23:45:51 +00007758 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007759 return BinaryOperator::CreateAnd(Shift,
7760 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007761 }
7762
7763 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007764 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007765 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007766 return 0;
7767}
7768
Chris Lattnera1be5662002-05-02 17:06:02 +00007769
Chris Lattnercfd65102005-10-29 04:36:15 +00007770/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7771/// expression. If so, decompose it, returning some value X, such that Val is
7772/// X*Scale+Offset.
7773///
7774static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007775 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007776 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007777 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007778 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007779 Scale = 0;
Owen Andersoneed707b2009-07-24 23:12:02 +00007780 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007781 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7782 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7783 if (I->getOpcode() == Instruction::Shl) {
7784 // This is a value scaled by '1 << the shift amt'.
7785 Scale = 1U << RHS->getZExtValue();
7786 Offset = 0;
7787 return I->getOperand(0);
7788 } else if (I->getOpcode() == Instruction::Mul) {
7789 // This value is scaled by 'RHS'.
7790 Scale = RHS->getZExtValue();
7791 Offset = 0;
7792 return I->getOperand(0);
7793 } else if (I->getOpcode() == Instruction::Add) {
7794 // We have X+C. Check to see if we really have (X*C2)+C1,
7795 // where C1 is divisible by C2.
7796 unsigned SubScale;
7797 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007798 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7799 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007800 Offset += RHS->getZExtValue();
7801 Scale = SubScale;
7802 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007803 }
7804 }
7805 }
7806
7807 // Otherwise, we can't look past this.
7808 Scale = 1;
7809 Offset = 0;
7810 return Val;
7811}
7812
7813
Chris Lattnerb3f83972005-10-24 06:03:58 +00007814/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7815/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007816Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007817 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007818 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007819
Chris Lattnerb53c2382005-10-24 06:22:12 +00007820 // Remove any uses of AI that are dead.
7821 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007822
Chris Lattnerb53c2382005-10-24 06:22:12 +00007823 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7824 Instruction *User = cast<Instruction>(*UI++);
7825 if (isInstructionTriviallyDead(User)) {
7826 while (UI != E && *UI == User)
7827 ++UI; // If this instruction uses AI more than once, don't break UI.
7828
Chris Lattnerb53c2382005-10-24 06:22:12 +00007829 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007830 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007831 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007832 }
7833 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007834
7835 // This requires TargetData to get the alloca alignment and size information.
7836 if (!TD) return 0;
7837
Chris Lattnerb3f83972005-10-24 06:03:58 +00007838 // Get the type really allocated and the type casted to.
7839 const Type *AllocElTy = AI.getAllocatedType();
7840 const Type *CastElTy = PTy->getElementType();
7841 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007842
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007843 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7844 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007845 if (CastElTyAlign < AllocElTyAlign) return 0;
7846
Chris Lattner39387a52005-10-24 06:35:18 +00007847 // If the allocation has multiple uses, only promote it if we are strictly
7848 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007849 // same, we open the door to infinite loops of various kinds. (A reference
7850 // from a dbg.declare doesn't count as a use for this purpose.)
7851 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7852 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007853
Duncan Sands777d2302009-05-09 07:06:46 +00007854 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7855 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007856 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007857
Chris Lattner455fcc82005-10-29 03:19:53 +00007858 // See if we can satisfy the modulus by pulling a scale out of the array
7859 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007860 unsigned ArraySizeScale;
7861 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007862 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007863 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7864 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007865
Chris Lattner455fcc82005-10-29 03:19:53 +00007866 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7867 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007868 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7869 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007870
Chris Lattner455fcc82005-10-29 03:19:53 +00007871 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7872 Value *Amt = 0;
7873 if (Scale == 1) {
7874 Amt = NumElements;
7875 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007876 // If the allocation size is constant, form a constant mul expression
Owen Andersoneed707b2009-07-24 23:12:02 +00007877 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007878 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007879 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007880 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007881 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007882 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007883 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007884 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007885 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007886 }
7887
Jeff Cohen86796be2007-04-04 16:58:57 +00007888 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneed707b2009-07-24 23:12:02 +00007889 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007890 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007891 Amt = InsertNewInstBefore(Tmp, AI);
7892 }
7893
Chris Lattnerb3f83972005-10-24 06:03:58 +00007894 AllocationInst *New;
7895 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007896 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007897 else
Owen Anderson50dead02009-07-15 23:53:25 +00007898 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007899 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007900 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007901
Dale Johannesena0a66372009-03-05 00:39:02 +00007902 // If the allocation has one real use plus a dbg.declare, just remove the
7903 // declare.
7904 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7905 EraseInstFromFunction(*DI);
7906 }
7907 // If the allocation has multiple real uses, insert a cast and change all
7908 // things that used it to use the new cast. This will also hack on CI, but it
7909 // will die soon.
7910 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007911 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007912 // New is the allocation instruction, pointer typed. AI is the original
7913 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7914 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007915 InsertNewInstBefore(NewCast, AI);
7916 AI.replaceAllUsesWith(NewCast);
7917 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007918 return ReplaceInstUsesWith(CI, New);
7919}
7920
Chris Lattner70074e02006-05-13 02:06:03 +00007921/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007922/// and return it as type Ty without inserting any new casts and without
7923/// changing the computed value. This is used by code that tries to decide
7924/// whether promoting or shrinking integer operations to wider or smaller types
7925/// will allow us to eliminate a truncate or extend.
7926///
7927/// This is a truncation operation if Ty is smaller than V->getType(), or an
7928/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007929///
7930/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7931/// should return true if trunc(V) can be computed by computing V in the smaller
7932/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7933/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7934/// efficiently truncated.
7935///
7936/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7937/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7938/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007939bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007940 unsigned CastOpc,
7941 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007942 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007943 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007944 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007945
7946 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 if (!I) return false;
7948
Dan Gohman6de29f82009-06-15 22:12:54 +00007949 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007950
Chris Lattner951626b2007-08-02 06:11:14 +00007951 // If this is an extension or truncate, we can often eliminate it.
7952 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7953 // If this is a cast from the destination type, we can trivially eliminate
7954 // it, and this will remove a cast overall.
7955 if (I->getOperand(0)->getType() == Ty) {
7956 // If the first operand is itself a cast, and is eliminable, do not count
7957 // this as an eliminable cast. We would prefer to eliminate those two
7958 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007959 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007960 ++NumCastsRemoved;
7961 return true;
7962 }
7963 }
7964
7965 // We can't extend or shrink something that has multiple uses: doing so would
7966 // require duplicating the instruction in general, which isn't profitable.
7967 if (!I->hasOneUse()) return false;
7968
Evan Chengf35fd542009-01-15 17:01:23 +00007969 unsigned Opc = I->getOpcode();
7970 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007971 case Instruction::Add:
7972 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007973 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007974 case Instruction::And:
7975 case Instruction::Or:
7976 case Instruction::Xor:
7977 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007978 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007979 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007980 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007981 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982
Eli Friedman070a9812009-07-13 22:46:01 +00007983 case Instruction::UDiv:
7984 case Instruction::URem: {
7985 // UDiv and URem can be truncated if all the truncated bits are zero.
7986 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7987 uint32_t BitWidth = Ty->getScalarSizeInBits();
7988 if (BitWidth < OrigBitWidth) {
7989 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7990 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7991 MaskedValueIsZero(I->getOperand(1), Mask)) {
7992 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7993 NumCastsRemoved) &&
7994 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7995 NumCastsRemoved);
7996 }
7997 }
7998 break;
7999 }
Chris Lattner46b96052006-11-29 07:18:39 +00008000 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008001 // If we are truncating the result of this SHL, and if it's a shift of a
8002 // constant amount, we can always perform a SHL in a smaller type.
8003 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008004 uint32_t BitWidth = Ty->getScalarSizeInBits();
8005 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008006 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008007 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008008 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008009 }
8010 break;
8011 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008012 // If this is a truncate of a logical shr, we can truncate it to a smaller
8013 // lshr iff we know that the bits we would otherwise be shifting in are
8014 // already zeros.
8015 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008016 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8017 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008018 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008019 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008020 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8021 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008022 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008023 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008024 }
8025 }
Chris Lattner46b96052006-11-29 07:18:39 +00008026 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008027 case Instruction::ZExt:
8028 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008029 case Instruction::Trunc:
8030 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008031 // can safely replace it. Note that replacing it does not reduce the number
8032 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008033 if (Opc == CastOpc)
8034 return true;
8035
8036 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008037 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008038 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008039 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008040 case Instruction::Select: {
8041 SelectInst *SI = cast<SelectInst>(I);
8042 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008043 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008044 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008045 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008046 }
Chris Lattner8114b712008-06-18 04:00:49 +00008047 case Instruction::PHI: {
8048 // We can change a phi if we can change all operands.
8049 PHINode *PN = cast<PHINode>(I);
8050 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8051 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008052 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008053 return false;
8054 return true;
8055 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008057 // TODO: Can handle more cases here.
8058 break;
8059 }
8060
8061 return false;
8062}
8063
8064/// EvaluateInDifferentType - Given an expression that
8065/// CanEvaluateInDifferentType returns true for, actually insert the code to
8066/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008067Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008068 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008069 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008070 return Context->getConstantExprIntegerCast(C, Ty,
8071 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008072
8073 // Otherwise, it must be an instruction.
8074 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008075 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008076 unsigned Opc = I->getOpcode();
8077 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008078 case Instruction::Add:
8079 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008080 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008081 case Instruction::And:
8082 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008083 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008084 case Instruction::AShr:
8085 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008086 case Instruction::Shl:
8087 case Instruction::UDiv:
8088 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008089 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008090 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008091 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008092 break;
8093 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008094 case Instruction::Trunc:
8095 case Instruction::ZExt:
8096 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008097 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008098 // just return the source. There's no need to insert it because it is not
8099 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008100 if (I->getOperand(0)->getType() == Ty)
8101 return I->getOperand(0);
8102
Chris Lattner8114b712008-06-18 04:00:49 +00008103 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008104 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008105 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008106 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008107 case Instruction::Select: {
8108 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8109 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8110 Res = SelectInst::Create(I->getOperand(0), True, False);
8111 break;
8112 }
Chris Lattner8114b712008-06-18 04:00:49 +00008113 case Instruction::PHI: {
8114 PHINode *OPN = cast<PHINode>(I);
8115 PHINode *NPN = PHINode::Create(Ty);
8116 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8117 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8118 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8119 }
8120 Res = NPN;
8121 break;
8122 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008123 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008124 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008125 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008126 break;
8127 }
8128
Chris Lattner8114b712008-06-18 04:00:49 +00008129 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008130 return InsertNewInstBefore(Res, *I);
8131}
8132
Reid Spencer3da59db2006-11-27 01:05:10 +00008133/// @brief Implement the transforms common to all CastInst visitors.
8134Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008135 Value *Src = CI.getOperand(0);
8136
Dan Gohman23d9d272007-05-11 21:10:54 +00008137 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008138 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008139 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008140 if (Instruction::CastOps opc =
8141 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8142 // The first cast (CSrc) is eliminable so we need to fix up or replace
8143 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008144 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008145 }
8146 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008147
Reid Spencer3da59db2006-11-27 01:05:10 +00008148 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008149 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8150 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8151 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008152
8153 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008154 if (isa<PHINode>(Src))
8155 if (Instruction *NV = FoldOpIntoPhi(CI))
8156 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008157
Reid Spencer3da59db2006-11-27 01:05:10 +00008158 return 0;
8159}
8160
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161/// FindElementAtOffset - Given a type and a constant offset, determine whether
8162/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008163/// the specified offset. If so, fill them into NewIndices and return the
8164/// resultant element type, otherwise return null.
8165static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8166 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008167 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008168 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008169 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008170 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171
8172 // Start with the index over the outer type. Note that the type size
8173 // might be zero (even if the offset isn't zero) if the indexed type
8174 // is something like [0 x {int, int}]
8175 const Type *IntPtrTy = TD->getIntPtrType();
8176 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008177 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008179 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008180
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008182 if (Offset < 0) {
8183 --FirstIdx;
8184 Offset += TySize;
8185 assert(Offset >= 0);
8186 }
8187 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8188 }
8189
Owen Andersoneed707b2009-07-24 23:12:02 +00008190 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008191
8192 // Index into the types. If we fail, set OrigBase to null.
8193 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008194 // Indexing into tail padding between struct/array elements.
8195 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008196 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008197
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8199 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008200 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8201 "Offset must stay within the indexed type");
8202
Chris Lattner46cd5a12009-01-09 05:44:56 +00008203 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneed707b2009-07-24 23:12:02 +00008204 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008205
8206 Offset -= SL->getElementOffset(Elt);
8207 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008208 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008209 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008210 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008211 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008212 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008213 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008214 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008215 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008216 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008217 }
8218 }
8219
Chris Lattner3914f722009-01-24 01:00:13 +00008220 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008221}
8222
Chris Lattnerd3e28342007-04-27 17:44:50 +00008223/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8224Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8225 Value *Src = CI.getOperand(0);
8226
Chris Lattnerd3e28342007-04-27 17:44:50 +00008227 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008228 // If casting the result of a getelementptr instruction with no offset, turn
8229 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230 if (GEP->hasAllZeroIndices()) {
8231 // Changing the cast operand is usually not a good idea but it is safe
8232 // here because the pointer operand is being replaced with another
8233 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008234 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008235 CI.setOperand(0, GEP->getOperand(0));
8236 return &CI;
8237 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008238
8239 // If the GEP has a single use, and the base pointer is a bitcast, and the
8240 // GEP computes a constant offset, see if we can convert these three
8241 // instructions into fewer. This typically happens with unions and other
8242 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008243 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008244 if (GEP->hasAllConstantIndices()) {
8245 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008246 ConstantInt *OffsetV =
8247 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008248 int64_t Offset = OffsetV->getSExtValue();
8249
8250 // Get the base pointer input of the bitcast, and the type it points to.
8251 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8252 const Type *GEPIdxTy =
8253 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008254 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008255 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008256 // If we were able to index down into an element, create the GEP
8257 // and bitcast the result. This eliminates one bitcast, potentially
8258 // two.
8259 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8260 NewIndices.begin(),
8261 NewIndices.end(), "");
8262 InsertNewInstBefore(NGEP, CI);
8263 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008264
Chris Lattner46cd5a12009-01-09 05:44:56 +00008265 if (isa<BitCastInst>(CI))
8266 return new BitCastInst(NGEP, CI.getType());
8267 assert(isa<PtrToIntInst>(CI));
8268 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008269 }
8270 }
8271 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008272 }
8273
8274 return commonCastTransforms(CI);
8275}
8276
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008277/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8278/// type like i42. We don't want to introduce operations on random non-legal
8279/// integer types where they don't already exist in the code. In the future,
8280/// we should consider making this based off target-data, so that 32-bit targets
8281/// won't get i64 operations etc.
8282static bool isSafeIntegerType(const Type *Ty) {
8283 switch (Ty->getPrimitiveSizeInBits()) {
8284 case 8:
8285 case 16:
8286 case 32:
8287 case 64:
8288 return true;
8289 default:
8290 return false;
8291 }
8292}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008293
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008294/// commonIntCastTransforms - This function implements the common transforms
8295/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008296Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8297 if (Instruction *Result = commonCastTransforms(CI))
8298 return Result;
8299
8300 Value *Src = CI.getOperand(0);
8301 const Type *SrcTy = Src->getType();
8302 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008303 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8304 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008305
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 // See if we can simplify any instructions used by the LHS whose sole
8307 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008308 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008309 return &CI;
8310
8311 // If the source isn't an instruction or has more than one use then we
8312 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008313 Instruction *SrcI = dyn_cast<Instruction>(Src);
8314 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 return 0;
8316
Chris Lattnerc739cd62007-03-03 05:27:34 +00008317 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008318 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008319 // Only do this if the dest type is a simple type, don't convert the
8320 // expression tree to something weird like i93 unless the source is also
8321 // strange.
8322 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008323 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8324 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008325 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008327 // eliminates the cast, so it is always a win. If this is a zero-extension,
8328 // we need to do an AND to maintain the clear top-part of the computation,
8329 // so we require that the input have eliminated at least one cast. If this
8330 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008331 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008332 bool DoXForm = false;
8333 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008334 switch (CI.getOpcode()) {
8335 default:
8336 // All the others use floating point so we shouldn't actually
8337 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008338 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008339 case Instruction::Trunc:
8340 DoXForm = true;
8341 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008342 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008343 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008344 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 // If it's unnecessary to issue an AND to clear the high bits, it's
8346 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008347 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008348 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8349 if (MaskedValueIsZero(TryRes, Mask))
8350 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008351
8352 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008353 if (TryI->use_empty())
8354 EraseInstFromFunction(*TryI);
8355 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008356 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357 }
Evan Chengf35fd542009-01-15 17:01:23 +00008358 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008359 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008360 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008361 // If we do not have to emit the truncate + sext pair, then it's always
8362 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008363 //
8364 // It's not safe to eliminate the trunc + sext pair if one of the
8365 // eliminated cast is a truncate. e.g.
8366 // t2 = trunc i32 t1 to i16
8367 // t3 = sext i16 t2 to i32
8368 // !=
8369 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008370 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008371 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8372 if (NumSignBits > (DestBitSize - SrcBitSize))
8373 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008374
8375 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008376 if (TryI->use_empty())
8377 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008378 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008379 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008380 }
Evan Chengf35fd542009-01-15 17:01:23 +00008381 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008382
8383 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008384 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8385 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008386 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8387 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008388 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008389 // Just replace this cast with the result.
8390 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008391
Reid Spencer3da59db2006-11-27 01:05:10 +00008392 assert(Res->getType() == DestTy);
8393 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008394 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008396 // Just replace this cast with the result.
8397 return ReplaceInstUsesWith(CI, Res);
8398 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008399 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008400
8401 // If the high bits are already zero, just replace this cast with the
8402 // result.
8403 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8404 if (MaskedValueIsZero(Res, Mask))
8405 return ReplaceInstUsesWith(CI, Res);
8406
8407 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008408 Constant *C = ConstantInt::get(*Context,
8409 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008410 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008411 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008412 case Instruction::SExt: {
8413 // If the high bits are already filled with sign bit, just replace this
8414 // cast with the result.
8415 unsigned NumSignBits = ComputeNumSignBits(Res);
8416 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008417 return ReplaceInstUsesWith(CI, Res);
8418
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008420 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008421 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8422 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008423 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008424 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008425 }
8426 }
8427
8428 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8429 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8430
8431 switch (SrcI->getOpcode()) {
8432 case Instruction::Add:
8433 case Instruction::Mul:
8434 case Instruction::And:
8435 case Instruction::Or:
8436 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008437 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008438 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8439 // Don't insert two casts unless at least one can be eliminated.
8440 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008441 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008442 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8443 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008444 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008445 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008446 }
8447 }
8448
8449 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8450 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8451 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008452 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008453 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008454 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008455 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008456 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008457 }
8458 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008459
Eli Friedman65445c52009-07-13 21:45:57 +00008460 case Instruction::Shl: {
8461 // Canonicalize trunc inside shl, if we can.
8462 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8463 if (CI && DestBitSize < SrcBitSize &&
8464 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8465 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8466 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008467 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008468 }
8469 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008470 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008471 }
8472 return 0;
8473}
8474
Chris Lattner8a9f5712007-04-11 06:57:46 +00008475Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008476 if (Instruction *Result = commonIntCastTransforms(CI))
8477 return Result;
8478
8479 Value *Src = CI.getOperand(0);
8480 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008481 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8482 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008483
8484 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008485 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008486 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008487 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008488 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008489 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008490 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008491
Chris Lattner4f9797d2009-03-24 18:15:30 +00008492 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8493 ConstantInt *ShAmtV = 0;
8494 Value *ShiftOp = 0;
8495 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008496 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008497 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8498
8499 // Get a mask for the bits shifting in.
8500 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8501 if (MaskedValueIsZero(ShiftOp, Mask)) {
8502 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008503 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008504
8505 // Okay, we can shrink this. Truncate the input, then return a new
8506 // shift.
8507 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008508 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008509 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008510 }
8511 }
8512
8513 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008514}
8515
Evan Chengb98a10e2008-03-24 00:21:34 +00008516/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8517/// in order to eliminate the icmp.
8518Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8519 bool DoXform) {
8520 // If we are just checking for a icmp eq of a single bit and zext'ing it
8521 // to an integer, then shift the bit to the appropriate place and then
8522 // cast to integer to avoid the comparison.
8523 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8524 const APInt &Op1CV = Op1C->getValue();
8525
8526 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8527 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8528 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8529 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8530 if (!DoXform) return ICI;
8531
8532 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008533 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008534 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008535 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008536 In->getName()+".lobit"),
8537 CI);
8538 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008539 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008540 false/*ZExt*/, "tmp", &CI);
8541
8542 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008543 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008544 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008545 In->getName()+".not"),
8546 CI);
8547 }
8548
8549 return ReplaceInstUsesWith(CI, In);
8550 }
8551
8552
8553
8554 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8555 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8556 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8557 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8558 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8559 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8560 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8561 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8562 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8563 // This only works for EQ and NE
8564 ICI->isEquality()) {
8565 // If Op1C some other power of two, convert:
8566 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8567 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8568 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8569 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8570
8571 APInt KnownZeroMask(~KnownZero);
8572 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8573 if (!DoXform) return ICI;
8574
8575 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8576 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8577 // (X&4) == 2 --> false
8578 // (X&4) != 2 --> true
Owen Andersoneed707b2009-07-24 23:12:02 +00008579 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Andersond672ecb2009-07-03 00:17:18 +00008580 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008581 return ReplaceInstUsesWith(CI, Res);
8582 }
8583
8584 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8585 Value *In = ICI->getOperand(0);
8586 if (ShiftAmt) {
8587 // Perform a logical shr by shiftamt.
8588 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008589 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008590 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008591 In->getName()+".lobit"), CI);
8592 }
8593
8594 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008595 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008596 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008597 InsertNewInstBefore(cast<Instruction>(In), CI);
8598 }
8599
8600 if (CI.getType() == In->getType())
8601 return ReplaceInstUsesWith(CI, In);
8602 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008603 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008604 }
8605 }
8606 }
8607
8608 return 0;
8609}
8610
Chris Lattner8a9f5712007-04-11 06:57:46 +00008611Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008612 // If one of the common conversion will work ..
8613 if (Instruction *Result = commonIntCastTransforms(CI))
8614 return Result;
8615
8616 Value *Src = CI.getOperand(0);
8617
Chris Lattnera84f47c2009-02-17 20:47:23 +00008618 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8619 // types and if the sizes are just right we can convert this into a logical
8620 // 'and' which will be much cheaper than the pair of casts.
8621 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8622 // Get the sizes of the types involved. We know that the intermediate type
8623 // will be smaller than A or C, but don't know the relation between A and C.
8624 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008625 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8626 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8627 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008628 // If we're actually extending zero bits, then if
8629 // SrcSize < DstSize: zext(a & mask)
8630 // SrcSize == DstSize: a & mask
8631 // SrcSize > DstSize: trunc(a) & mask
8632 if (SrcSize < DstSize) {
8633 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008634 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008635 Instruction *And =
8636 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8637 InsertNewInstBefore(And, CI);
8638 return new ZExtInst(And, CI.getType());
8639 } else if (SrcSize == DstSize) {
8640 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008641 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008642 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008643 } else if (SrcSize > DstSize) {
8644 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8645 InsertNewInstBefore(Trunc, CI);
8646 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008647 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008648 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008649 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008650 }
8651 }
8652
Evan Chengb98a10e2008-03-24 00:21:34 +00008653 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8654 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008655
Evan Chengb98a10e2008-03-24 00:21:34 +00008656 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8657 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8658 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8659 // of the (zext icmp) will be transformed.
8660 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8661 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8662 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8663 (transformZExtICmp(LHS, CI, false) ||
8664 transformZExtICmp(RHS, CI, false))) {
8665 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8666 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008667 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008668 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008669 }
8670
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008671 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008672 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8673 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8674 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8675 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008676 if (TI0->getType() == CI.getType())
8677 return
8678 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008679 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008680 }
8681
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008682 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8683 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8684 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8685 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8686 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8687 And->getOperand(1) == C)
8688 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8689 Value *TI0 = TI->getOperand(0);
8690 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008691 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008692 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8693 InsertNewInstBefore(NewAnd, *And);
8694 return BinaryOperator::CreateXor(NewAnd, ZC);
8695 }
8696 }
8697
Reid Spencer3da59db2006-11-27 01:05:10 +00008698 return 0;
8699}
8700
Chris Lattner8a9f5712007-04-11 06:57:46 +00008701Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008702 if (Instruction *I = commonIntCastTransforms(CI))
8703 return I;
8704
Chris Lattner8a9f5712007-04-11 06:57:46 +00008705 Value *Src = CI.getOperand(0);
8706
Dan Gohman1975d032008-10-30 20:40:10 +00008707 // Canonicalize sign-extend from i1 to a select.
8708 if (Src->getType() == Type::Int1Ty)
8709 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008710 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008711 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008712
8713 // See if the value being truncated is already sign extended. If so, just
8714 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008715 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008716 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008717 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8718 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8719 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008720 unsigned NumSignBits = ComputeNumSignBits(Op);
8721
8722 if (OpBits == DestBits) {
8723 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8724 // bits, it is already ready.
8725 if (NumSignBits > DestBits-MidBits)
8726 return ReplaceInstUsesWith(CI, Op);
8727 } else if (OpBits < DestBits) {
8728 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8729 // bits, just sext from i32.
8730 if (NumSignBits > OpBits-MidBits)
8731 return new SExtInst(Op, CI.getType(), "tmp");
8732 } else {
8733 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8734 // bits, just truncate to i32.
8735 if (NumSignBits > OpBits-MidBits)
8736 return new TruncInst(Op, CI.getType(), "tmp");
8737 }
8738 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008739
8740 // If the input is a shl/ashr pair of a same constant, then this is a sign
8741 // extension from a smaller value. If we could trust arbitrary bitwidth
8742 // integers, we could turn this into a truncate to the smaller bit and then
8743 // use a sext for the whole extension. Since we don't, look deeper and check
8744 // for a truncate. If the source and dest are the same type, eliminate the
8745 // trunc and extend and just do shifts. For example, turn:
8746 // %a = trunc i32 %i to i8
8747 // %b = shl i8 %a, 6
8748 // %c = ashr i8 %b, 6
8749 // %d = sext i8 %c to i32
8750 // into:
8751 // %a = shl i32 %i, 30
8752 // %d = ashr i32 %a, 30
8753 Value *A = 0;
8754 ConstantInt *BA = 0, *CA = 0;
8755 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008756 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008757 BA == CA && isa<TruncInst>(A)) {
8758 Value *I = cast<TruncInst>(A)->getOperand(0);
8759 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008760 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8761 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008762 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008763 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008764 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8765 CI.getName()), CI);
8766 return BinaryOperator::CreateAShr(I, ShAmtV);
8767 }
8768 }
8769
Chris Lattnerba417832007-04-11 06:12:58 +00008770 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008771}
8772
Chris Lattnerb7530652008-01-27 05:29:54 +00008773/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8774/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008775static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008776 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008777 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008778 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008779 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8780 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008781 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008782 return 0;
8783}
8784
8785/// LookThroughFPExtensions - If this is an fp extension instruction, look
8786/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008787static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008788 if (Instruction *I = dyn_cast<Instruction>(V))
8789 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008790 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008791
8792 // If this value is a constant, return the constant in the smallest FP type
8793 // that can accurately represent it. This allows us to turn
8794 // (float)((double)X+2.0) into x+2.0f.
8795 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8796 if (CFP->getType() == Type::PPC_FP128Ty)
8797 return V; // No constant folding of this.
8798 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008799 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 return V;
8801 if (CFP->getType() == Type::DoubleTy)
8802 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008803 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 return V;
8805 // Don't try to shrink to various long double types.
8806 }
8807
8808 return V;
8809}
8810
8811Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8812 if (Instruction *I = commonCastTransforms(CI))
8813 return I;
8814
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008815 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008817 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008818 // many builtins (sqrt, etc).
8819 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8820 if (OpI && OpI->hasOneUse()) {
8821 switch (OpI->getOpcode()) {
8822 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008823 case Instruction::FAdd:
8824 case Instruction::FSub:
8825 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008826 case Instruction::FDiv:
8827 case Instruction::FRem:
8828 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008829 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8830 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008831 if (LHSTrunc->getType() != SrcTy &&
8832 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008833 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008834 // If the source types were both smaller than the destination type of
8835 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008836 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8837 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008838 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8839 CI.getType(), CI);
8840 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8841 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008842 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008843 }
8844 }
8845 break;
8846 }
8847 }
8848 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008849}
8850
8851Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8852 return commonCastTransforms(CI);
8853}
8854
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008855Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008856 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8857 if (OpI == 0)
8858 return commonCastTransforms(FI);
8859
8860 // fptoui(uitofp(X)) --> X
8861 // fptoui(sitofp(X)) --> X
8862 // This is safe if the intermediate type has enough bits in its mantissa to
8863 // accurately represent all values of X. For example, do not do this with
8864 // i64->float->i64. This is also safe for sitofp case, because any negative
8865 // 'X' value would cause an undefined result for the fptoui.
8866 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8867 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008868 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008869 OpI->getType()->getFPMantissaWidth())
8870 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008871
8872 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008873}
8874
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008875Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008876 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8877 if (OpI == 0)
8878 return commonCastTransforms(FI);
8879
8880 // fptosi(sitofp(X)) --> X
8881 // fptosi(uitofp(X)) --> X
8882 // This is safe if the intermediate type has enough bits in its mantissa to
8883 // accurately represent all values of X. For example, do not do this with
8884 // i64->float->i64. This is also safe for sitofp case, because any negative
8885 // 'X' value would cause an undefined result for the fptoui.
8886 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8887 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008888 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008889 OpI->getType()->getFPMantissaWidth())
8890 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008891
8892 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008893}
8894
8895Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8896 return commonCastTransforms(CI);
8897}
8898
8899Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8900 return commonCastTransforms(CI);
8901}
8902
Chris Lattnera0e69692009-03-24 18:35:40 +00008903Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8904 // If the destination integer type is smaller than the intptr_t type for
8905 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8906 // trunc to be exposed to other transforms. Don't do this for extending
8907 // ptrtoint's, because we don't know if the target sign or zero extends its
8908 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008909 if (TD &&
8910 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008911 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8912 TD->getIntPtrType(),
8913 "tmp"), CI);
8914 return new TruncInst(P, CI.getType());
8915 }
8916
Chris Lattnerd3e28342007-04-27 17:44:50 +00008917 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008918}
8919
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008920Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008921 // If the source integer type is larger than the intptr_t type for
8922 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8923 // allows the trunc to be exposed to other transforms. Don't do this for
8924 // extending inttoptr's, because we don't know if the target sign or zero
8925 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008926 if (TD &&
8927 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008928 TD->getPointerSizeInBits()) {
8929 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8930 TD->getIntPtrType(),
8931 "tmp"), CI);
8932 return new IntToPtrInst(P, CI.getType());
8933 }
8934
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008935 if (Instruction *I = commonCastTransforms(CI))
8936 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008937
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008938 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008939}
8940
Chris Lattnerd3e28342007-04-27 17:44:50 +00008941Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008942 // If the operands are integer typed then apply the integer transforms,
8943 // otherwise just apply the common ones.
8944 Value *Src = CI.getOperand(0);
8945 const Type *SrcTy = Src->getType();
8946 const Type *DestTy = CI.getType();
8947
Eli Friedman7e25d452009-07-13 20:53:00 +00008948 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008949 if (Instruction *I = commonPointerCastTransforms(CI))
8950 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008951 } else {
8952 if (Instruction *Result = commonCastTransforms(CI))
8953 return Result;
8954 }
8955
8956
8957 // Get rid of casts from one type to the same type. These are useless and can
8958 // be replaced by the operand.
8959 if (DestTy == Src->getType())
8960 return ReplaceInstUsesWith(CI, Src);
8961
Reid Spencer3da59db2006-11-27 01:05:10 +00008962 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008963 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8964 const Type *DstElTy = DstPTy->getElementType();
8965 const Type *SrcElTy = SrcPTy->getElementType();
8966
Nate Begeman83ad90a2008-03-31 00:22:16 +00008967 // If the address spaces don't match, don't eliminate the bitcast, which is
8968 // required for changing types.
8969 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8970 return 0;
8971
Chris Lattnerd3e28342007-04-27 17:44:50 +00008972 // If we are casting a malloc or alloca to a pointer to a type of the same
8973 // size, rewrite the allocation instruction to allocate the "right" type.
8974 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8975 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8976 return V;
8977
Chris Lattnerd717c182007-05-05 22:32:24 +00008978 // If the source and destination are pointers, and this cast is equivalent
8979 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008980 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008981 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008982 unsigned NumZeros = 0;
8983 while (SrcElTy != DstElTy &&
8984 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8985 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8986 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8987 ++NumZeros;
8988 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008989
Chris Lattnerd3e28342007-04-27 17:44:50 +00008990 // If we found a path from the src to dest, create the getelementptr now.
8991 if (SrcElTy == DstElTy) {
8992 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008993 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8994 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008995 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008996 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008997
Eli Friedman2451a642009-07-18 23:06:53 +00008998 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8999 if (DestVTy->getNumElements() == 1) {
9000 if (!isa<VectorType>(SrcTy)) {
9001 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9002 DestVTy->getElementType(), CI);
9003 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
9004 Context->getNullValue(Type::Int32Ty));
9005 }
9006 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9007 }
9008 }
9009
9010 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9011 if (SrcVTy->getNumElements() == 1) {
9012 if (!isa<VectorType>(DestTy)) {
9013 Instruction *Elem =
9014 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
9015 InsertNewInstBefore(Elem, CI);
9016 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9017 }
9018 }
9019 }
9020
Reid Spencer3da59db2006-11-27 01:05:10 +00009021 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9022 if (SVI->hasOneUse()) {
9023 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9024 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009025 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009026 cast<VectorType>(DestTy)->getNumElements() ==
9027 SVI->getType()->getNumElements() &&
9028 SVI->getType()->getNumElements() ==
9029 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009030 CastInst *Tmp;
9031 // If either of the operands is a cast from CI.getType(), then
9032 // evaluating the shuffle in the casted destination's type will allow
9033 // us to eliminate at least one cast.
9034 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9035 Tmp->getOperand(0)->getType() == DestTy) ||
9036 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9037 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009038 Value *LHS = InsertCastBefore(Instruction::BitCast,
9039 SVI->getOperand(0), DestTy, CI);
9040 Value *RHS = InsertCastBefore(Instruction::BitCast,
9041 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009042 // Return a new shuffle vector. Use the same element ID's, as we
9043 // know the vector types match #elts.
9044 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009045 }
9046 }
9047 }
9048 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009049 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009050}
9051
Chris Lattnere576b912004-04-09 23:46:01 +00009052/// GetSelectFoldableOperands - We want to turn code that looks like this:
9053/// %C = or %A, %B
9054/// %D = select %cond, %C, %A
9055/// into:
9056/// %C = select %cond, %B, 0
9057/// %D = or %A, %C
9058///
9059/// Assuming that the specified instruction is an operand to the select, return
9060/// a bitmask indicating which operands of this instruction are foldable if they
9061/// equal the other incoming value of the select.
9062///
9063static unsigned GetSelectFoldableOperands(Instruction *I) {
9064 switch (I->getOpcode()) {
9065 case Instruction::Add:
9066 case Instruction::Mul:
9067 case Instruction::And:
9068 case Instruction::Or:
9069 case Instruction::Xor:
9070 return 3; // Can fold through either operand.
9071 case Instruction::Sub: // Can only fold on the amount subtracted.
9072 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009073 case Instruction::LShr:
9074 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009075 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009076 default:
9077 return 0; // Cannot fold
9078 }
9079}
9080
9081/// GetSelectFoldableConstant - For the same transformation as the previous
9082/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009083static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009084 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009085 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009086 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009087 case Instruction::Add:
9088 case Instruction::Sub:
9089 case Instruction::Or:
9090 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009091 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009092 case Instruction::LShr:
9093 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009094 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009095 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009096 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009097 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009098 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009099 }
9100}
9101
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009102/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9103/// have the same opcode and only one use each. Try to simplify this.
9104Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9105 Instruction *FI) {
9106 if (TI->getNumOperands() == 1) {
9107 // If this is a non-volatile load or a cast from the same type,
9108 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009109 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009110 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9111 return 0;
9112 } else {
9113 return 0; // unknown unary op.
9114 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009115
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009116 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009117 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9118 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009120 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009121 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009122 }
9123
Reid Spencer832254e2007-02-02 02:16:23 +00009124 // Only handle binary operators here.
9125 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009126 return 0;
9127
9128 // Figure out if the operations have any operands in common.
9129 Value *MatchOp, *OtherOpT, *OtherOpF;
9130 bool MatchIsOpZero;
9131 if (TI->getOperand(0) == FI->getOperand(0)) {
9132 MatchOp = TI->getOperand(0);
9133 OtherOpT = TI->getOperand(1);
9134 OtherOpF = FI->getOperand(1);
9135 MatchIsOpZero = true;
9136 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9137 MatchOp = TI->getOperand(1);
9138 OtherOpT = TI->getOperand(0);
9139 OtherOpF = FI->getOperand(0);
9140 MatchIsOpZero = false;
9141 } else if (!TI->isCommutative()) {
9142 return 0;
9143 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9144 MatchOp = TI->getOperand(0);
9145 OtherOpT = TI->getOperand(1);
9146 OtherOpF = FI->getOperand(0);
9147 MatchIsOpZero = true;
9148 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9149 MatchOp = TI->getOperand(1);
9150 OtherOpT = TI->getOperand(0);
9151 OtherOpF = FI->getOperand(1);
9152 MatchIsOpZero = true;
9153 } else {
9154 return 0;
9155 }
9156
9157 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009158 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9159 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009160 InsertNewInstBefore(NewSI, SI);
9161
9162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9163 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009164 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009165 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009166 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009167 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009168 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009169 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009170}
9171
Evan Chengde621922009-03-31 20:42:45 +00009172static bool isSelect01(Constant *C1, Constant *C2) {
9173 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9174 if (!C1I)
9175 return false;
9176 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9177 if (!C2I)
9178 return false;
9179 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9180}
9181
9182/// FoldSelectIntoOp - Try fold the select into one of the operands to
9183/// facilitate further optimization.
9184Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9185 Value *FalseVal) {
9186 // See the comment above GetSelectFoldableOperands for a description of the
9187 // transformation we are doing here.
9188 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9189 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9190 !isa<Constant>(FalseVal)) {
9191 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9192 unsigned OpToFold = 0;
9193 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9194 OpToFold = 1;
9195 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9196 OpToFold = 2;
9197 }
9198
9199 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009200 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009201 Value *OOp = TVI->getOperand(2-OpToFold);
9202 // Avoid creating select between 2 constants unless it's selecting
9203 // between 0 and 1.
9204 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9205 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9206 InsertNewInstBefore(NewSel, SI);
9207 NewSel->takeName(TVI);
9208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9209 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009210 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009211 }
9212 }
9213 }
9214 }
9215 }
9216
9217 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9218 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9219 !isa<Constant>(TrueVal)) {
9220 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9221 unsigned OpToFold = 0;
9222 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9223 OpToFold = 1;
9224 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9225 OpToFold = 2;
9226 }
9227
9228 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009229 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009230 Value *OOp = FVI->getOperand(2-OpToFold);
9231 // Avoid creating select between 2 constants unless it's selecting
9232 // between 0 and 1.
9233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9234 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9235 InsertNewInstBefore(NewSel, SI);
9236 NewSel->takeName(FVI);
9237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9238 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009239 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009240 }
9241 }
9242 }
9243 }
9244 }
9245
9246 return 0;
9247}
9248
Dan Gohman81b28ce2008-09-16 18:46:06 +00009249/// visitSelectInstWithICmp - Visit a SelectInst that has an
9250/// ICmpInst as its first operand.
9251///
9252Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9253 ICmpInst *ICI) {
9254 bool Changed = false;
9255 ICmpInst::Predicate Pred = ICI->getPredicate();
9256 Value *CmpLHS = ICI->getOperand(0);
9257 Value *CmpRHS = ICI->getOperand(1);
9258 Value *TrueVal = SI.getTrueValue();
9259 Value *FalseVal = SI.getFalseValue();
9260
9261 // Check cases where the comparison is with a constant that
9262 // can be adjusted to fit the min/max idiom. We may edit ICI in
9263 // place here, so make sure the select is the only user.
9264 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009265 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009266 switch (Pred) {
9267 default: break;
9268 case ICmpInst::ICMP_ULT:
9269 case ICmpInst::ICMP_SLT: {
9270 // X < MIN ? T : F --> F
9271 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9272 return ReplaceInstUsesWith(SI, FalseVal);
9273 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009274 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009275 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9276 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9277 Pred = ICmpInst::getSwappedPredicate(Pred);
9278 CmpRHS = AdjustedRHS;
9279 std::swap(FalseVal, TrueVal);
9280 ICI->setPredicate(Pred);
9281 ICI->setOperand(1, CmpRHS);
9282 SI.setOperand(1, TrueVal);
9283 SI.setOperand(2, FalseVal);
9284 Changed = true;
9285 }
9286 break;
9287 }
9288 case ICmpInst::ICMP_UGT:
9289 case ICmpInst::ICMP_SGT: {
9290 // X > MAX ? T : F --> F
9291 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9292 return ReplaceInstUsesWith(SI, FalseVal);
9293 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009294 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009295 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9296 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9297 Pred = ICmpInst::getSwappedPredicate(Pred);
9298 CmpRHS = AdjustedRHS;
9299 std::swap(FalseVal, TrueVal);
9300 ICI->setPredicate(Pred);
9301 ICI->setOperand(1, CmpRHS);
9302 SI.setOperand(1, TrueVal);
9303 SI.setOperand(2, FalseVal);
9304 Changed = true;
9305 }
9306 break;
9307 }
9308 }
9309
Dan Gohman1975d032008-10-30 20:40:10 +00009310 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9311 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009312 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009313 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9314 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009315 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009316 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9317 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009318 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9319
Dan Gohman1975d032008-10-30 20:40:10 +00009320 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9321 // If we are just checking for a icmp eq of a single bit and zext'ing it
9322 // to an integer, then shift the bit to the appropriate place and then
9323 // cast to integer to avoid the comparison.
9324 const APInt &Op1CV = CI->getValue();
9325
9326 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9327 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9328 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009329 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009330 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009331 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009332 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009333 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9334 In->getName()+".lobit"),
9335 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009336 if (In->getType() != SI.getType())
9337 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009338 true/*SExt*/, "tmp", ICI);
9339
9340 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009341 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009342 In->getName()+".not"), *ICI);
9343
9344 return ReplaceInstUsesWith(SI, In);
9345 }
9346 }
9347 }
9348
Dan Gohman81b28ce2008-09-16 18:46:06 +00009349 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9350 // Transform (X == Y) ? X : Y -> Y
9351 if (Pred == ICmpInst::ICMP_EQ)
9352 return ReplaceInstUsesWith(SI, FalseVal);
9353 // Transform (X != Y) ? X : Y -> X
9354 if (Pred == ICmpInst::ICMP_NE)
9355 return ReplaceInstUsesWith(SI, TrueVal);
9356 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9357
9358 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9359 // Transform (X == Y) ? Y : X -> X
9360 if (Pred == ICmpInst::ICMP_EQ)
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 // Transform (X != Y) ? Y : X -> Y
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
9368 /// NOTE: if we wanted to, this is where to detect integer ABS
9369
9370 return Changed ? &SI : 0;
9371}
9372
Chris Lattner3d69f462004-03-12 05:52:32 +00009373Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009374 Value *CondVal = SI.getCondition();
9375 Value *TrueVal = SI.getTrueValue();
9376 Value *FalseVal = SI.getFalseValue();
9377
9378 // select true, X, Y -> X
9379 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009380 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009381 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009382
9383 // select C, X, X -> X
9384 if (TrueVal == FalseVal)
9385 return ReplaceInstUsesWith(SI, TrueVal);
9386
Chris Lattnere87597f2004-10-16 18:11:37 +00009387 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9388 return ReplaceInstUsesWith(SI, FalseVal);
9389 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9390 return ReplaceInstUsesWith(SI, TrueVal);
9391 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9392 if (isa<Constant>(TrueVal))
9393 return ReplaceInstUsesWith(SI, TrueVal);
9394 else
9395 return ReplaceInstUsesWith(SI, FalseVal);
9396 }
9397
Reid Spencer4fe16d62007-01-11 18:21:29 +00009398 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009399 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009400 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009401 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009402 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009403 } else {
9404 // Change: A = select B, false, C --> A = and !B, C
9405 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009406 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009407 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009409 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009410 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009411 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009412 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009413 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009414 } else {
9415 // Change: A = select B, C, true --> A = or !B, C
9416 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009417 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009418 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009420 }
9421 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009422
9423 // select a, b, a -> a&b
9424 // select a, a, b -> a|b
9425 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009426 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009427 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009428 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009429 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009430
Chris Lattner2eefe512004-04-09 19:05:30 +00009431 // Selecting between two integer constants?
9432 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9433 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009434 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009435 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009436 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009437 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009438 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009439 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009440 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009441 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009442 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009443 }
Chris Lattner457dd822004-06-09 07:59:58 +00009444
Reid Spencere4d87aa2006-12-23 06:05:41 +00009445 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009446 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009447 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009448 // non-constant value, eliminate this whole mess. This corresponds to
9449 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009450 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009451 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009452 cast<Constant>(IC->getOperand(1))->isNullValue())
9453 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9454 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009455 isa<ConstantInt>(ICA->getOperand(1)) &&
9456 (ICA->getOperand(1) == TrueValC ||
9457 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009458 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9459 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009460 // know whether we have a icmp_ne or icmp_eq and whether the
9461 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009462 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009463 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009464 Value *V = ICA;
9465 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009466 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009467 Instruction::Xor, V, ICA->getOperand(1)), SI);
9468 return ReplaceInstUsesWith(SI, V);
9469 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009470 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009471 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009472
9473 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009474 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9475 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009476 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009477 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9478 // This is not safe in general for floating point:
9479 // consider X== -0, Y== +0.
9480 // It becomes safe if either operand is a nonzero constant.
9481 ConstantFP *CFPt, *CFPf;
9482 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9483 !CFPt->getValueAPF().isZero()) ||
9484 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9485 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009486 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009487 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009488 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009489 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009490 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009491 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009492
Reid Spencere4d87aa2006-12-23 06:05:41 +00009493 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009494 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009495 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9496 // This is not safe in general for floating point:
9497 // consider X== -0, Y== +0.
9498 // It becomes safe if either operand is a nonzero constant.
9499 ConstantFP *CFPt, *CFPf;
9500 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9501 !CFPt->getValueAPF().isZero()) ||
9502 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9503 !CFPf->getValueAPF().isZero()))
9504 return ReplaceInstUsesWith(SI, FalseVal);
9505 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009506 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009507 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9508 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009509 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009510 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009511 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009512 }
9513
9514 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009515 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9516 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9517 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009518
Chris Lattner87875da2005-01-13 22:52:24 +00009519 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9520 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9521 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009522 Instruction *AddOp = 0, *SubOp = 0;
9523
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009524 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9525 if (TI->getOpcode() == FI->getOpcode())
9526 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9527 return IV;
9528
9529 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9530 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009531 if ((TI->getOpcode() == Instruction::Sub &&
9532 FI->getOpcode() == Instruction::Add) ||
9533 (TI->getOpcode() == Instruction::FSub &&
9534 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009535 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009536 } else if ((FI->getOpcode() == Instruction::Sub &&
9537 TI->getOpcode() == Instruction::Add) ||
9538 (FI->getOpcode() == Instruction::FSub &&
9539 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009540 AddOp = TI; SubOp = FI;
9541 }
9542
9543 if (AddOp) {
9544 Value *OtherAddOp = 0;
9545 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9546 OtherAddOp = AddOp->getOperand(1);
9547 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9548 OtherAddOp = AddOp->getOperand(0);
9549 }
9550
9551 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009552 // So at this point we know we have (Y -> OtherAddOp):
9553 // select C, (add X, Y), (sub X, Z)
9554 Value *NegVal; // Compute -Z
9555 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009556 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009557 } else {
9558 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009559 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9560 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009561 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009562
9563 Value *NewTrueOp = OtherAddOp;
9564 Value *NewFalseOp = NegVal;
9565 if (AddOp != TI)
9566 std::swap(NewTrueOp, NewFalseOp);
9567 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009568 SelectInst::Create(CondVal, NewTrueOp,
9569 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009570
9571 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009572 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009573 }
9574 }
9575 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009576
Chris Lattnere576b912004-04-09 23:46:01 +00009577 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009578 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009579 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9580 if (FoldI)
9581 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009582 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009583
9584 if (BinaryOperator::isNot(CondVal)) {
9585 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9586 SI.setOperand(1, FalseVal);
9587 SI.setOperand(2, TrueVal);
9588 return &SI;
9589 }
9590
Chris Lattner3d69f462004-03-12 05:52:32 +00009591 return 0;
9592}
9593
Dan Gohmaneee962e2008-04-10 18:43:06 +00009594/// EnforceKnownAlignment - If the specified pointer points to an object that
9595/// we control, modify the object's alignment to PrefAlign. This isn't
9596/// often possible though. If alignment is important, a more reliable approach
9597/// is to simply align all global variables and allocation instructions to
9598/// their preferred alignment from the beginning.
9599///
9600static unsigned EnforceKnownAlignment(Value *V,
9601 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009602
Dan Gohmaneee962e2008-04-10 18:43:06 +00009603 User *U = dyn_cast<User>(V);
9604 if (!U) return Align;
9605
Dan Gohmanca178902009-07-17 20:47:02 +00009606 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009607 default: break;
9608 case Instruction::BitCast:
9609 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9610 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009611 // If all indexes are zero, it is just the alignment of the base pointer.
9612 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009613 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009614 if (!isa<Constant>(*i) ||
9615 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009616 AllZeroOperands = false;
9617 break;
9618 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009619
9620 if (AllZeroOperands) {
9621 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009622 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009623 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009624 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009625 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009626 }
9627
9628 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9629 // If there is a large requested alignment and we can, bump up the alignment
9630 // of the global.
9631 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009632 if (GV->getAlignment() >= PrefAlign)
9633 Align = GV->getAlignment();
9634 else {
9635 GV->setAlignment(PrefAlign);
9636 Align = PrefAlign;
9637 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009638 }
9639 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9640 // If there is a requested alignment and if this is an alloca, round up. We
9641 // don't do this for malloc, because some systems can't respect the request.
9642 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009643 if (AI->getAlignment() >= PrefAlign)
9644 Align = AI->getAlignment();
9645 else {
9646 AI->setAlignment(PrefAlign);
9647 Align = PrefAlign;
9648 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009649 }
9650 }
9651
9652 return Align;
9653}
9654
9655/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9656/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9657/// and it is more than the alignment of the ultimate object, see if we can
9658/// increase the alignment of the ultimate object, making this check succeed.
9659unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9660 unsigned PrefAlign) {
9661 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9662 sizeof(PrefAlign) * CHAR_BIT;
9663 APInt Mask = APInt::getAllOnesValue(BitWidth);
9664 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9665 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9666 unsigned TrailZ = KnownZero.countTrailingOnes();
9667 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9668
9669 if (PrefAlign > Align)
9670 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9671
9672 // We don't need to make any adjustment.
9673 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009674}
9675
Chris Lattnerf497b022008-01-13 23:50:23 +00009676Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009677 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009678 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009679 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009680 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009681
9682 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009683 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009684 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009685 return MI;
9686 }
9687
9688 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9689 // load/store.
9690 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9691 if (MemOpLength == 0) return 0;
9692
Chris Lattner37ac6082008-01-14 00:28:35 +00009693 // Source and destination pointer types are always "i8*" for intrinsic. See
9694 // if the size is something we can handle with a single primitive load/store.
9695 // A single load+store correctly handles overlapping memory in the memmove
9696 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009697 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009698 if (Size == 0) return MI; // Delete this mem transfer.
9699
9700 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009701 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009702
Chris Lattner37ac6082008-01-14 00:28:35 +00009703 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009704 Type *NewPtrTy =
9705 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009706
9707 // Memcpy forces the use of i8* for the source and destination. That means
9708 // that if you're using memcpy to move one double around, you'll get a cast
9709 // from double* to i8*. We'd much rather use a double load+store rather than
9710 // an i64 load+store, here because this improves the odds that the source or
9711 // dest address will be promotable. See if we can find a better type than the
9712 // integer datatype.
9713 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9714 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009715 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9717 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009718 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009719 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9720 if (STy->getNumElements() == 1)
9721 SrcETy = STy->getElementType(0);
9722 else
9723 break;
9724 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9725 if (ATy->getNumElements() == 1)
9726 SrcETy = ATy->getElementType();
9727 else
9728 break;
9729 } else
9730 break;
9731 }
9732
Dan Gohman8f8e2692008-05-23 01:52:21 +00009733 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009734 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009735 }
9736 }
9737
9738
Chris Lattnerf497b022008-01-13 23:50:23 +00009739 // If the memcpy/memmove provides better alignment info than we can
9740 // infer, use it.
9741 SrcAlign = std::max(SrcAlign, CopyAlign);
9742 DstAlign = std::max(DstAlign, CopyAlign);
9743
9744 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9745 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009746 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9747 InsertNewInstBefore(L, *MI);
9748 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9749
9750 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009751 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009752 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009753}
Chris Lattner3d69f462004-03-12 05:52:32 +00009754
Chris Lattner69ea9d22008-04-30 06:39:11 +00009755Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9756 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009757 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009758 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009759 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009760 return MI;
9761 }
9762
9763 // Extract the length and alignment and fill if they are constant.
9764 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9765 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9766 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9767 return 0;
9768 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009769 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009770
9771 // If the length is zero, this is a no-op
9772 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9773
9774 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9775 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009776 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009779 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009780
9781 // Alignment 0 is identity for alignment 1 for memset, but not store.
9782 if (Alignment == 0) Alignment = 1;
9783
9784 // Extract the fill value and store.
9785 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009786 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009787 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788
9789 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009790 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009791 return MI;
9792 }
9793
9794 return 0;
9795}
9796
9797
Chris Lattner8b0ea312006-01-13 20:11:04 +00009798/// visitCallInst - CallInst simplification. This mostly only handles folding
9799/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9800/// the heavy lifting.
9801///
Chris Lattner9fe38862003-06-19 17:00:31 +00009802Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009803 // If the caller function is nounwind, mark the call as nounwind, even if the
9804 // callee isn't.
9805 if (CI.getParent()->getParent()->doesNotThrow() &&
9806 !CI.doesNotThrow()) {
9807 CI.setDoesNotThrow();
9808 return &CI;
9809 }
9810
9811
9812
Chris Lattner8b0ea312006-01-13 20:11:04 +00009813 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9814 if (!II) return visitCallSite(&CI);
9815
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009816 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9817 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009818 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009819 bool Changed = false;
9820
9821 // memmove/cpy/set of zero bytes is a noop.
9822 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9823 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9824
Chris Lattner35b9e482004-10-12 04:52:52 +00009825 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009826 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009827 // Replace the instruction with just byte operations. We would
9828 // transform other cases to loads/stores, but we don't know if
9829 // alignment is sufficient.
9830 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009831 }
9832
Chris Lattner35b9e482004-10-12 04:52:52 +00009833 // If we have a memmove and the source operation is a constant global,
9834 // then the source and dest pointers can't alias, so we can change this
9835 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009836 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009837 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9838 if (GVSrc->isConstant()) {
9839 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009840 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9841 const Type *Tys[1];
9842 Tys[0] = CI.getOperand(3)->getType();
9843 CI.setOperand(0,
9844 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009845 Changed = true;
9846 }
Chris Lattnera935db82008-05-28 05:30:41 +00009847
9848 // memmove(x,x,size) -> noop.
9849 if (MMI->getSource() == MMI->getDest())
9850 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009851 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009852
Chris Lattner95a959d2006-03-06 20:18:44 +00009853 // If we can determine a pointer alignment that is bigger than currently
9854 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009855 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009856 if (Instruction *I = SimplifyMemTransfer(MI))
9857 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009858 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9859 if (Instruction *I = SimplifyMemSet(MSI))
9860 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009861 }
9862
Chris Lattner8b0ea312006-01-13 20:11:04 +00009863 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 }
9865
9866 switch (II->getIntrinsicID()) {
9867 default: break;
9868 case Intrinsic::bswap:
9869 // bswap(bswap(x)) -> x
9870 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9871 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9872 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9873 break;
9874 case Intrinsic::ppc_altivec_lvx:
9875 case Intrinsic::ppc_altivec_lvxl:
9876 case Intrinsic::x86_sse_loadu_ps:
9877 case Intrinsic::x86_sse2_loadu_pd:
9878 case Intrinsic::x86_sse2_loadu_dq:
9879 // Turn PPC lvx -> load if the pointer is known aligned.
9880 // Turn X86 loadups -> load if the pointer is known aligned.
9881 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9882 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009883 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009884 CI);
9885 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009886 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009887 break;
9888 case Intrinsic::ppc_altivec_stvx:
9889 case Intrinsic::ppc_altivec_stvxl:
9890 // Turn stvx -> store if the pointer is known aligned.
9891 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9892 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009893 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009894 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9895 return new StoreInst(II->getOperand(1), Ptr);
9896 }
9897 break;
9898 case Intrinsic::x86_sse_storeu_ps:
9899 case Intrinsic::x86_sse2_storeu_pd:
9900 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009901 // Turn X86 storeu -> store if the pointer is known aligned.
9902 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9903 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009904 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009905 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9906 return new StoreInst(II->getOperand(2), Ptr);
9907 }
9908 break;
9909
9910 case Intrinsic::x86_sse_cvttss2si: {
9911 // These intrinsics only demands the 0th element of its input vector. If
9912 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009913 unsigned VWidth =
9914 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9915 APInt DemandedElts(VWidth, 1);
9916 APInt UndefElts(VWidth, 0);
9917 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009918 UndefElts)) {
9919 II->setOperand(1, V);
9920 return II;
9921 }
9922 break;
9923 }
9924
9925 case Intrinsic::ppc_altivec_vperm:
9926 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9927 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9928 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009929
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 // Check that all of the elements are integer constants or undefs.
9931 bool AllEltsOk = true;
9932 for (unsigned i = 0; i != 16; ++i) {
9933 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9934 !isa<UndefValue>(Mask->getOperand(i))) {
9935 AllEltsOk = false;
9936 break;
9937 }
9938 }
9939
9940 if (AllEltsOk) {
9941 // Cast the input vectors to byte vectors.
9942 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9943 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009944 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009945
Chris Lattner0521e3c2008-06-18 04:33:20 +00009946 // Only extract each element once.
9947 Value *ExtractedElts[32];
9948 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9949
Chris Lattnere2ed0572006-04-06 19:19:17 +00009950 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009951 if (isa<UndefValue>(Mask->getOperand(i)))
9952 continue;
9953 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9954 Idx &= 31; // Match the hardware behavior.
9955
9956 if (ExtractedElts[Idx] == 0) {
9957 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009958 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
Owen Andersoneed707b2009-07-24 23:12:02 +00009959 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009960 InsertNewInstBefore(Elt, CI);
9961 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009962 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009963
Chris Lattner0521e3c2008-06-18 04:33:20 +00009964 // Insert this value into the result vector.
9965 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneed707b2009-07-24 23:12:02 +00009966 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009967 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009968 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009969 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009971 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 }
9973 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 case Intrinsic::stackrestore: {
9976 // If the save is right next to the restore, remove the restore. This can
9977 // happen when variable allocas are DCE'd.
9978 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9979 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9980 BasicBlock::iterator BI = SS;
9981 if (&*++BI == II)
9982 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009983 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009984 }
9985
9986 // Scan down this block to see if there is another stack restore in the
9987 // same block without an intervening call/alloca.
9988 BasicBlock::iterator BI = II;
9989 TerminatorInst *TI = II->getParent()->getTerminator();
9990 bool CannotRemove = false;
9991 for (++BI; &*BI != TI; ++BI) {
9992 if (isa<AllocaInst>(BI)) {
9993 CannotRemove = true;
9994 break;
9995 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009996 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9997 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9998 // If there is a stackrestore below this one, remove this one.
9999 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10000 return EraseInstFromFunction(CI);
10001 // Otherwise, ignore the intrinsic.
10002 } else {
10003 // If we found a non-intrinsic call, we can't remove the stack
10004 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010005 CannotRemove = true;
10006 break;
10007 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010008 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010009 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010010
10011 // If the stack restore is in a return/unwind block and if there are no
10012 // allocas or calls between the restore and the return, nuke the restore.
10013 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10014 return EraseInstFromFunction(CI);
10015 break;
10016 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010017 }
10018
Chris Lattner8b0ea312006-01-13 20:11:04 +000010019 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010020}
10021
10022// InvokeInst simplification
10023//
10024Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010025 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010026}
10027
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010028/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10029/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010030static bool isSafeToEliminateVarargsCast(const CallSite CS,
10031 const CastInst * const CI,
10032 const TargetData * const TD,
10033 const int ix) {
10034 if (!CI->isLosslessCast())
10035 return false;
10036
10037 // The size of ByVal arguments is derived from the type, so we
10038 // can't change to a type with a different size. If the size were
10039 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010040 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010041 return true;
10042
10043 const Type* SrcTy =
10044 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10045 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10046 if (!SrcTy->isSized() || !DstTy->isSized())
10047 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010048 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010049 return false;
10050 return true;
10051}
10052
Chris Lattnera44d8a22003-10-07 22:32:43 +000010053// visitCallSite - Improvements for call and invoke instructions.
10054//
10055Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010056 bool Changed = false;
10057
10058 // If the callee is a constexpr cast of a function, attempt to move the cast
10059 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010060 if (transformConstExprCastCall(CS)) return 0;
10061
Chris Lattner6c266db2003-10-07 22:54:13 +000010062 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010063
Chris Lattner08b22ec2005-05-13 07:09:09 +000010064 if (Function *CalleeF = dyn_cast<Function>(Callee))
10065 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10066 Instruction *OldCall = CS.getInstruction();
10067 // If the call and callee calling conventions don't match, this call must
10068 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010069 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010070 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10071 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010072 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010073 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010074 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10075 return EraseInstFromFunction(*OldCall);
10076 return 0;
10077 }
10078
Chris Lattner17be6352004-10-18 02:59:09 +000010079 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10080 // This instruction is not reachable, just remove it. We insert a store to
10081 // undef so that we know that this code is not reachable, despite the fact
10082 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010083 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010084 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010085 CS.getInstruction());
10086
10087 if (!CS.getInstruction()->use_empty())
10088 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010089 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010090
10091 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10092 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010093 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010094 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010095 }
Chris Lattner17be6352004-10-18 02:59:09 +000010096 return EraseInstFromFunction(*CS.getInstruction());
10097 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010098
Duncan Sandscdb6d922007-09-17 10:26:40 +000010099 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10100 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10101 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10102 return transformCallThroughTrampoline(CS);
10103
Chris Lattner6c266db2003-10-07 22:54:13 +000010104 const PointerType *PTy = cast<PointerType>(Callee->getType());
10105 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10106 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010107 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010108 // See if we can optimize any arguments passed through the varargs area of
10109 // the call.
10110 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010111 E = CS.arg_end(); I != E; ++I, ++ix) {
10112 CastInst *CI = dyn_cast<CastInst>(*I);
10113 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10114 *I = CI->getOperand(0);
10115 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010116 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010117 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010118 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010119
Duncan Sandsf0c33542007-12-19 21:13:37 +000010120 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010121 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010122 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010123 Changed = true;
10124 }
10125
Chris Lattner6c266db2003-10-07 22:54:13 +000010126 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010127}
10128
Chris Lattner9fe38862003-06-19 17:00:31 +000010129// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10130// attempt to move the cast to the arguments of the call/invoke.
10131//
10132bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10133 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10134 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010135 if (CE->getOpcode() != Instruction::BitCast ||
10136 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010137 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010138 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010139 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010140 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010141
10142 // Okay, this is a cast from a function to a different type. Unless doing so
10143 // would cause a type conversion of one of our arguments, change this call to
10144 // be a direct call with arguments casted to the appropriate types.
10145 //
10146 const FunctionType *FT = Callee->getFunctionType();
10147 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010148 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010149
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010150 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010151 return false; // TODO: Handle multiple return values.
10152
Chris Lattnerf78616b2004-01-14 06:06:08 +000010153 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010154 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010155 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010156 // Conversion is ok if changing from one pointer type to another or from
10157 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010158 !((isa<PointerType>(OldRetTy) || !TD ||
10159 OldRetTy == TD->getIntPtrType()) &&
10160 (isa<PointerType>(NewRetTy) || !TD ||
10161 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010162 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010163
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010164 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010166 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010167 return false; // Cannot transform this return value.
10168
Chris Lattner58d74912008-03-12 17:45:29 +000010169 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010170 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010171 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010172 return false; // Attribute not compatible with transformed value.
10173 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010174
Chris Lattnerf78616b2004-01-14 06:06:08 +000010175 // If the callsite is an invoke instruction, and the return value is used by
10176 // a PHI node in a successor, we cannot change the return type of the call
10177 // because there is no place to put the cast instruction (without breaking
10178 // the critical edge). Bail out in this case.
10179 if (!Caller->use_empty())
10180 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10181 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10182 UI != E; ++UI)
10183 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10184 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010185 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010186 return false;
10187 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010188
10189 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10190 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010191
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 CallSite::arg_iterator AI = CS.arg_begin();
10193 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10194 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010195 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010196
10197 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010198 return false; // Cannot transform this parameter value.
10199
Devang Patel19c87462008-09-26 22:53:05 +000010200 if (CallerPAL.getParamAttributes(i + 1)
10201 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010202 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010203
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010204 // Converting from one pointer type to another or between a pointer and an
10205 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010206 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010207 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10208 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010209 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010210 }
10211
10212 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010213 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010214 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010215
Chris Lattner58d74912008-03-12 17:45:29 +000010216 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10217 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010218 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010219 // won't be dropping them. Check that these extra arguments have attributes
10220 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010221 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10222 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010223 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010224 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010225 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010226 return false;
10227 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010228
Chris Lattner9fe38862003-06-19 17:00:31 +000010229 // Okay, we decided that this is a safe thing to do: go ahead and start
10230 // inserting cast instructions as necessary...
10231 std::vector<Value*> Args;
10232 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010233 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010234 attrVec.reserve(NumCommonArgs);
10235
10236 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010237 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010238
10239 // If the return value is not being used, the type may not be compatible
10240 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010241 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010242
10243 // Add the new return attributes.
10244 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010245 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010246
10247 AI = CS.arg_begin();
10248 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10249 const Type *ParamTy = FT->getParamType(i);
10250 if ((*AI)->getType() == ParamTy) {
10251 Args.push_back(*AI);
10252 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010253 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010254 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010255 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010256 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010258
10259 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010260 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010261 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010262 }
10263
10264 // If the function takes more arguments than the call was taking, add them
10265 // now...
10266 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010267 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010268
10269 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010270 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010271 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010272 cerr << "WARNING: While resolving call to function '"
10273 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010274 } else {
10275 // Add all of the arguments in their promoted form to the arg list...
10276 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10277 const Type *PTy = getPromotedType((*AI)->getType());
10278 if (PTy != (*AI)->getType()) {
10279 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010280 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10281 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010282 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010283 InsertNewInstBefore(Cast, *Caller);
10284 Args.push_back(Cast);
10285 } else {
10286 Args.push_back(*AI);
10287 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010288
Duncan Sandse1e520f2008-01-13 08:02:44 +000010289 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010290 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010291 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010292 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010294 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010295
Devang Patel19c87462008-09-26 22:53:05 +000010296 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10297 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10298
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010299 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010300 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010301
Devang Patel05988662008-09-25 21:00:45 +000010302 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010303
Chris Lattner9fe38862003-06-19 17:00:31 +000010304 Instruction *NC;
10305 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010306 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010307 Args.begin(), Args.end(),
10308 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010309 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010310 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010311 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010312 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10313 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010314 CallInst *CI = cast<CallInst>(Caller);
10315 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010316 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010317 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010318 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010319 }
10320
Chris Lattner6934a042007-02-11 01:23:03 +000010321 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010322 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010323 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010324 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010325 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010326 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010327 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010328
10329 // If this is an invoke instruction, we should insert it after the first
10330 // non-phi, instruction in the normal successor block.
10331 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010332 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010333 InsertNewInstBefore(NC, *I);
10334 } else {
10335 // Otherwise, it's a call, just insert cast right after the call instr
10336 InsertNewInstBefore(NC, *Caller);
10337 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010338 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010339 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010340 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010341 }
10342 }
10343
10344 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10345 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010346 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010347 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010348 return true;
10349}
10350
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351// transformCallThroughTrampoline - Turn a call to a function created by the
10352// init_trampoline intrinsic into a direct call to the underlying function.
10353//
10354Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10355 Value *Callee = CS.getCalledValue();
10356 const PointerType *PTy = cast<PointerType>(Callee->getType());
10357 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010358 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010359
10360 // If the call already has the 'nest' attribute somewhere then give up -
10361 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010362 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010363 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010364
10365 IntrinsicInst *Tramp =
10366 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10367
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010368 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10370 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10371
Devang Patel05988662008-09-25 21:00:45 +000010372 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010373 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010374 unsigned NestIdx = 1;
10375 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010376 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010377
10378 // Look for a parameter marked with the 'nest' attribute.
10379 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10380 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010381 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 // Record the parameter type and any other attributes.
10383 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010384 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385 break;
10386 }
10387
10388 if (NestTy) {
10389 Instruction *Caller = CS.getInstruction();
10390 std::vector<Value*> NewArgs;
10391 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10392
Devang Patel05988662008-09-25 21:00:45 +000010393 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010394 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397 // mean appending it. Likewise for attributes.
10398
Devang Patel19c87462008-09-26 22:53:05 +000010399 // Add any result attributes.
10400 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010401 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010402
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403 {
10404 unsigned Idx = 1;
10405 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10406 do {
10407 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 Value *NestVal = Tramp->getOperand(3);
10410 if (NestVal->getType() != NestTy)
10411 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10412 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010413 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414 }
10415
10416 if (I == E)
10417 break;
10418
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010419 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010421 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010422 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010423 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424
10425 ++Idx, ++I;
10426 } while (1);
10427 }
10428
Devang Patel19c87462008-09-26 22:53:05 +000010429 // Add any function attributes.
10430 if (Attributes Attr = Attrs.getFnAttributes())
10431 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10432
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 // The trampoline may have been bitcast to a bogus type (FTy).
10434 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010435 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010436
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 NewTypes.reserve(FTy->getNumParams()+1);
10439
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 {
10443 unsigned Idx = 1;
10444 FunctionType::param_iterator I = FTy->param_begin(),
10445 E = FTy->param_end();
10446
10447 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010448 if (Idx == NestIdx)
10449 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010450 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010451
10452 if (I == E)
10453 break;
10454
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010455 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010456 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457
10458 ++Idx, ++I;
10459 } while (1);
10460 }
10461
10462 // Replace the trampoline call with a direct call. Let the generic
10463 // code sort out any function type mismatches.
10464 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010465 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10466 FTy->isVarArg());
10467 Constant *NewCallee =
10468 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10469 NestF : Context->getConstantExprBitCast(NestF,
10470 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010471 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472
10473 Instruction *NewCaller;
10474 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010475 NewCaller = InvokeInst::Create(NewCallee,
10476 II->getNormalDest(), II->getUnwindDest(),
10477 NewArgs.begin(), NewArgs.end(),
10478 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010480 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010482 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10483 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010484 if (cast<CallInst>(Caller)->isTailCall())
10485 cast<CallInst>(NewCaller)->setTailCall();
10486 cast<CallInst>(NewCaller)->
10487 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010488 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489 }
10490 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10491 Caller->replaceAllUsesWith(NewCaller);
10492 Caller->eraseFromParent();
10493 RemoveFromWorkList(Caller);
10494 return 0;
10495 }
10496 }
10497
10498 // Replace the trampoline call with a direct call. Since there is no 'nest'
10499 // parameter, there is no need to adjust the argument list. Let the generic
10500 // code sort out any function type mismatches.
10501 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010502 NestF->getType() == PTy ? NestF :
10503 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010504 CS.setCalledFunction(NewCallee);
10505 return CS.getInstruction();
10506}
10507
Chris Lattner7da52b22006-11-01 04:51:18 +000010508/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10509/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10510/// and a single binop.
10511Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10512 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010513 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010514 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010515 Value *LHSVal = FirstInst->getOperand(0);
10516 Value *RHSVal = FirstInst->getOperand(1);
10517
10518 const Type *LHSType = LHSVal->getType();
10519 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010520
10521 // Scan to see if all operands are the same opcode, all have one use, and all
10522 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010523 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010524 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010525 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010526 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010527 // types or GEP's with different index types.
10528 I->getOperand(0)->getType() != LHSType ||
10529 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010530 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010531
10532 // If they are CmpInst instructions, check their predicates
10533 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10534 if (cast<CmpInst>(I)->getPredicate() !=
10535 cast<CmpInst>(FirstInst)->getPredicate())
10536 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010537
10538 // Keep track of which operand needs a phi node.
10539 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10540 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010541 }
10542
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010543 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010544
Chris Lattner7da52b22006-11-01 04:51:18 +000010545 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010546 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010547 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010548 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010549 NewLHS = PHINode::Create(LHSType,
10550 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010551 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10552 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010553 InsertNewInstBefore(NewLHS, PN);
10554 LHSVal = NewLHS;
10555 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010556
10557 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010558 NewRHS = PHINode::Create(RHSType,
10559 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010560 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10561 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010562 InsertNewInstBefore(NewRHS, PN);
10563 RHSVal = NewRHS;
10564 }
10565
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010566 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010567 if (NewLHS || NewRHS) {
10568 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10569 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10570 if (NewLHS) {
10571 Value *NewInLHS = InInst->getOperand(0);
10572 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10573 }
10574 if (NewRHS) {
10575 Value *NewInRHS = InInst->getOperand(1);
10576 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10577 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010578 }
10579 }
10580
Chris Lattner7da52b22006-11-01 04:51:18 +000010581 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010582 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010583 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010584 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10585 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010586}
10587
Chris Lattner05f18922008-12-01 02:34:36 +000010588Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10589 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10590
10591 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10592 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010593 // This is true if all GEP bases are allocas and if all indices into them are
10594 // constants.
10595 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010596
10597 // Scan to see if all operands are the same opcode, all have one use, and all
10598 // kill their operands (i.e. the operands have one use).
10599 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10600 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10601 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10602 GEP->getNumOperands() != FirstInst->getNumOperands())
10603 return 0;
10604
Chris Lattner36d3e322009-02-21 00:46:50 +000010605 // Keep track of whether or not all GEPs are of alloca pointers.
10606 if (AllBasePointersAreAllocas &&
10607 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10608 !GEP->hasAllConstantIndices()))
10609 AllBasePointersAreAllocas = false;
10610
Chris Lattner05f18922008-12-01 02:34:36 +000010611 // Compare the operand lists.
10612 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10613 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10614 continue;
10615
10616 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10617 // if one of the PHIs has a constant for the index. The index may be
10618 // substantially cheaper to compute for the constants, so making it a
10619 // variable index could pessimize the path. This also handles the case
10620 // for struct indices, which must always be constant.
10621 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10622 isa<ConstantInt>(GEP->getOperand(op)))
10623 return 0;
10624
10625 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10626 return 0;
10627 FixedOperands[op] = 0; // Needs a PHI.
10628 }
10629 }
10630
Chris Lattner36d3e322009-02-21 00:46:50 +000010631 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010632 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010633 // offset calculation, but all the predecessors will have to materialize the
10634 // stack address into a register anyway. We'd actually rather *clone* the
10635 // load up into the predecessors so that we have a load of a gep of an alloca,
10636 // which can usually all be folded into the load.
10637 if (AllBasePointersAreAllocas)
10638 return 0;
10639
Chris Lattner05f18922008-12-01 02:34:36 +000010640 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10641 // that is variable.
10642 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10643
10644 bool HasAnyPHIs = false;
10645 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10646 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10647 Value *FirstOp = FirstInst->getOperand(i);
10648 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10649 FirstOp->getName()+".pn");
10650 InsertNewInstBefore(NewPN, PN);
10651
10652 NewPN->reserveOperandSpace(e);
10653 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10654 OperandPhis[i] = NewPN;
10655 FixedOperands[i] = NewPN;
10656 HasAnyPHIs = true;
10657 }
10658
10659
10660 // Add all operands to the new PHIs.
10661 if (HasAnyPHIs) {
10662 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10663 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10664 BasicBlock *InBB = PN.getIncomingBlock(i);
10665
10666 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10667 if (PHINode *OpPhi = OperandPhis[op])
10668 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10669 }
10670 }
10671
10672 Value *Base = FixedOperands[0];
10673 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10674 FixedOperands.end());
10675}
10676
10677
Chris Lattner21550882009-02-23 05:56:17 +000010678/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10679/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010680/// obvious the value of the load is not changed from the point of the load to
10681/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010682///
10683/// Finally, it is safe, but not profitable, to sink a load targetting a
10684/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10685/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010686static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010687 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10688
10689 for (++BBI; BBI != E; ++BBI)
10690 if (BBI->mayWriteToMemory())
10691 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010692
10693 // Check for non-address taken alloca. If not address-taken already, it isn't
10694 // profitable to do this xform.
10695 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10696 bool isAddressTaken = false;
10697 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10698 UI != E; ++UI) {
10699 if (isa<LoadInst>(UI)) continue;
10700 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10701 // If storing TO the alloca, then the address isn't taken.
10702 if (SI->getOperand(1) == AI) continue;
10703 }
10704 isAddressTaken = true;
10705 break;
10706 }
10707
Chris Lattner36d3e322009-02-21 00:46:50 +000010708 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010709 return false;
10710 }
10711
Chris Lattner36d3e322009-02-21 00:46:50 +000010712 // If this load is a load from a GEP with a constant offset from an alloca,
10713 // then we don't want to sink it. In its present form, it will be
10714 // load [constant stack offset]. Sinking it will cause us to have to
10715 // materialize the stack addresses in each predecessor in a register only to
10716 // do a shared load from register in the successor.
10717 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10718 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10719 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10720 return false;
10721
Chris Lattner76c73142006-11-01 07:13:54 +000010722 return true;
10723}
10724
Chris Lattner9fe38862003-06-19 17:00:31 +000010725
Chris Lattnerbac32862004-11-14 19:13:23 +000010726// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10727// operator and they all are only used by the PHI, PHI together their
10728// inputs, and do the operation once, to the result of the PHI.
10729Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10730 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10731
10732 // Scan the instruction, looking for input operations that can be folded away.
10733 // If all input operands to the phi are the same instruction (e.g. a cast from
10734 // the same type or "+42") we can pull the operation through the PHI, reducing
10735 // code size and simplifying code.
10736 Constant *ConstantOp = 0;
10737 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010738 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010739 if (isa<CastInst>(FirstInst)) {
10740 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010741 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010742 // Can fold binop, compare or shift here if the RHS is a constant,
10743 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010744 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010745 if (ConstantOp == 0)
10746 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010747 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10748 isVolatile = LI->isVolatile();
10749 // We can't sink the load if the loaded value could be modified between the
10750 // load and the PHI.
10751 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010752 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010753 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010754
10755 // If the PHI is of volatile loads and the load block has multiple
10756 // successors, sinking it would remove a load of the volatile value from
10757 // the path through the other successor.
10758 if (isVolatile &&
10759 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10760 return 0;
10761
Chris Lattner9c080502006-11-01 07:43:41 +000010762 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010763 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010764 } else {
10765 return 0; // Cannot fold this operation.
10766 }
10767
10768 // Check to see if all arguments are the same operation.
10769 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10770 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10771 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010772 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010773 return 0;
10774 if (CastSrcTy) {
10775 if (I->getOperand(0)->getType() != CastSrcTy)
10776 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010777 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010778 // We can't sink the load if the loaded value could be modified between
10779 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010780 if (LI->isVolatile() != isVolatile ||
10781 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010782 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010783 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010784
Chris Lattner71042962008-07-08 17:18:32 +000010785 // If the PHI is of volatile loads and the load block has multiple
10786 // successors, sinking it would remove a load of the volatile value from
10787 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010788 if (isVolatile &&
10789 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10790 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010791
Chris Lattnerbac32862004-11-14 19:13:23 +000010792 } else if (I->getOperand(1) != ConstantOp) {
10793 return 0;
10794 }
10795 }
10796
10797 // Okay, they are all the same operation. Create a new PHI node of the
10798 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010799 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10800 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010801 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010802
10803 Value *InVal = FirstInst->getOperand(0);
10804 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010805
10806 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010807 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10808 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10809 if (NewInVal != InVal)
10810 InVal = 0;
10811 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10812 }
10813
10814 Value *PhiVal;
10815 if (InVal) {
10816 // The new PHI unions all of the same values together. This is really
10817 // common, so we handle it intelligently here for compile-time speed.
10818 PhiVal = InVal;
10819 delete NewPN;
10820 } else {
10821 InsertNewInstBefore(NewPN, PN);
10822 PhiVal = NewPN;
10823 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010824
Chris Lattnerbac32862004-11-14 19:13:23 +000010825 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010826 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010827 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010828 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010829 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010830 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010831 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010832 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010833 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10834
10835 // If this was a volatile load that we are merging, make sure to loop through
10836 // and mark all the input loads as non-volatile. If we don't do this, we will
10837 // insert a new volatile load and the old ones will not be deletable.
10838 if (isVolatile)
10839 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10840 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10841
10842 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010843}
Chris Lattnera1be5662002-05-02 17:06:02 +000010844
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010845/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10846/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010847static bool DeadPHICycle(PHINode *PN,
10848 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010849 if (PN->use_empty()) return true;
10850 if (!PN->hasOneUse()) return false;
10851
10852 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010853 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010854 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010855
10856 // Don't scan crazily complex things.
10857 if (PotentiallyDeadPHIs.size() == 16)
10858 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010859
10860 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10861 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010862
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010863 return false;
10864}
10865
Chris Lattnercf5008a2007-11-06 21:52:06 +000010866/// PHIsEqualValue - Return true if this phi node is always equal to
10867/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10868/// z = some value; x = phi (y, z); y = phi (x, z)
10869static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10870 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10871 // See if we already saw this PHI node.
10872 if (!ValueEqualPHIs.insert(PN))
10873 return true;
10874
10875 // Don't scan crazily complex things.
10876 if (ValueEqualPHIs.size() == 16)
10877 return false;
10878
10879 // Scan the operands to see if they are either phi nodes or are equal to
10880 // the value.
10881 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10882 Value *Op = PN->getIncomingValue(i);
10883 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10884 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10885 return false;
10886 } else if (Op != NonPhiInVal)
10887 return false;
10888 }
10889
10890 return true;
10891}
10892
10893
Chris Lattner473945d2002-05-06 18:06:38 +000010894// PHINode simplification
10895//
Chris Lattner7e708292002-06-25 16:13:24 +000010896Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010897 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010898 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010899
Owen Anderson7e057142006-07-10 22:03:18 +000010900 if (Value *V = PN.hasConstantValue())
10901 return ReplaceInstUsesWith(PN, V);
10902
Owen Anderson7e057142006-07-10 22:03:18 +000010903 // If all PHI operands are the same operation, pull them through the PHI,
10904 // reducing code size.
10905 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010906 isa<Instruction>(PN.getIncomingValue(1)) &&
10907 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10908 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10909 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10910 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010911 PN.getIncomingValue(0)->hasOneUse())
10912 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10913 return Result;
10914
10915 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10916 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10917 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010918 if (PN.hasOneUse()) {
10919 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10920 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010921 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010922 PotentiallyDeadPHIs.insert(&PN);
10923 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010924 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010925 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010926
10927 // If this phi has a single use, and if that use just computes a value for
10928 // the next iteration of a loop, delete the phi. This occurs with unused
10929 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10930 // common case here is good because the only other things that catch this
10931 // are induction variable analysis (sometimes) and ADCE, which is only run
10932 // late.
10933 if (PHIUser->hasOneUse() &&
10934 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10935 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010936 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010937 }
10938 }
Owen Anderson7e057142006-07-10 22:03:18 +000010939
Chris Lattnercf5008a2007-11-06 21:52:06 +000010940 // We sometimes end up with phi cycles that non-obviously end up being the
10941 // same value, for example:
10942 // z = some value; x = phi (y, z); y = phi (x, z)
10943 // where the phi nodes don't necessarily need to be in the same block. Do a
10944 // quick check to see if the PHI node only contains a single non-phi value, if
10945 // so, scan to see if the phi cycle is actually equal to that value.
10946 {
10947 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10948 // Scan for the first non-phi operand.
10949 while (InValNo != NumOperandVals &&
10950 isa<PHINode>(PN.getIncomingValue(InValNo)))
10951 ++InValNo;
10952
10953 if (InValNo != NumOperandVals) {
10954 Value *NonPhiInVal = PN.getOperand(InValNo);
10955
10956 // Scan the rest of the operands to see if there are any conflicts, if so
10957 // there is no need to recursively scan other phis.
10958 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10959 Value *OpVal = PN.getIncomingValue(InValNo);
10960 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10961 break;
10962 }
10963
10964 // If we scanned over all operands, then we have one unique value plus
10965 // phi values. Scan PHI nodes to see if they all merge in each other or
10966 // the value.
10967 if (InValNo == NumOperandVals) {
10968 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10969 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10970 return ReplaceInstUsesWith(PN, NonPhiInVal);
10971 }
10972 }
10973 }
Chris Lattner60921c92003-12-19 05:58:40 +000010974 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010975}
10976
Reid Spencer17212df2006-12-12 09:18:51 +000010977static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10978 Instruction *InsertPoint,
10979 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010980 unsigned PtrSize = DTy->getScalarSizeInBits();
10981 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010982 // We must cast correctly to the pointer type. Ensure that we
10983 // sign extend the integer value if it is smaller as this is
10984 // used for address computation.
10985 Instruction::CastOps opcode =
10986 (VTySize < PtrSize ? Instruction::SExt :
10987 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10988 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010989}
10990
Chris Lattnera1be5662002-05-02 17:06:02 +000010991
Chris Lattner7e708292002-06-25 16:13:24 +000010992Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010993 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010994 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010995 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010996 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010997 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010998
Chris Lattnere87597f2004-10-16 18:11:37 +000010999 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011000 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011001
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011002 bool HasZeroPointerIndex = false;
11003 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11004 HasZeroPointerIndex = C->isNullValue();
11005
11006 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011007 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011008
Chris Lattner28977af2004-04-05 01:30:19 +000011009 // Eliminate unneeded casts for indices.
11010 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011011
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011012 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011013 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11014 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011015 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011016 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011017 if (CI->getOpcode() == Instruction::ZExt ||
11018 CI->getOpcode() == Instruction::SExt) {
11019 const Type *SrcTy = CI->getOperand(0)->getType();
11020 // We can eliminate a cast from i32 to i64 iff the target
11021 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011022 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011023 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011024 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011025 }
11026 }
11027 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011028 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011029 // to what we need. If narrower, sign-extend it to what we need.
11030 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011031 // insert it. This explicit cast can make subsequent optimizations more
11032 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011033 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011034 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011035 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011036 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011037 MadeChange = true;
11038 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011039 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11040 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011041 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011042 MadeChange = true;
11043 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011044 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11045 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011046 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011047 MadeChange = true;
11048 } else {
11049 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11050 GEP);
11051 *i = Op;
11052 MadeChange = true;
11053 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011054 }
Chris Lattner28977af2004-04-05 01:30:19 +000011055 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011056 }
Chris Lattner28977af2004-04-05 01:30:19 +000011057 if (MadeChange) return &GEP;
11058
Chris Lattner90ac28c2002-08-02 19:29:35 +000011059 // Combine Indices - If the source pointer to this getelementptr instruction
11060 // is a getelementptr instruction, combine the indices of the two
11061 // getelementptr instructions into a single instruction.
11062 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011063 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011064 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011065 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011066
11067 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011068 // Note that if our source is a gep chain itself that we wait for that
11069 // chain to be resolved before we perform this transformation. This
11070 // avoids us creating a TON of code in some cases.
11071 //
11072 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11073 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11074 return 0; // Wait until our source is folded to completion.
11075
Chris Lattner72588fc2007-02-15 22:48:32 +000011076 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011077
11078 // Find out whether the last index in the source GEP is a sequential idx.
11079 bool EndsWithSequential = false;
11080 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11081 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011082 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011083
Chris Lattner90ac28c2002-08-02 19:29:35 +000011084 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011085 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011086 // Replace: gep (gep %P, long B), long A, ...
11087 // With: T = long A+B; gep %P, T, ...
11088 //
Chris Lattner620ce142004-05-07 22:09:22 +000011089 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011090 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011091 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011092 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011093 Sum = SO1;
11094 } else {
11095 // If they aren't the same type, convert both to an integer of the
11096 // target's pointer size.
11097 if (SO1->getType() != GO1->getType()) {
11098 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011099 SO1 =
11100 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011101 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011102 GO1 =
11103 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011104 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011105 unsigned PS = TD->getPointerSizeInBits();
11106 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011107 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011108 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011109
Duncan Sands514ab342007-11-01 20:53:16 +000011110 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011111 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011112 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011113 } else {
11114 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011115 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11116 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011117 }
11118 }
11119 }
Chris Lattner620ce142004-05-07 22:09:22 +000011120 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011121 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11122 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011123 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011124 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011125 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011126 }
Chris Lattner28977af2004-04-05 01:30:19 +000011127 }
Chris Lattner620ce142004-05-07 22:09:22 +000011128
11129 // Recycle the GEP we already have if possible.
11130 if (SrcGEPOperands.size() == 2) {
11131 GEP.setOperand(0, SrcGEPOperands[0]);
11132 GEP.setOperand(1, Sum);
11133 return &GEP;
11134 } else {
11135 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11136 SrcGEPOperands.end()-1);
11137 Indices.push_back(Sum);
11138 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11139 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011140 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011141 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011142 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011143 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011144 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11145 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011146 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11147 }
11148
11149 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011150 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11151 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011152
Chris Lattner620ce142004-05-07 22:09:22 +000011153 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011154 // GEP of global variable. If all of the indices for this GEP are
11155 // constants, we can promote this to a constexpr instead of an instruction.
11156
11157 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011158 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011159 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11160 for (; I != E && isa<Constant>(*I); ++I)
11161 Indices.push_back(cast<Constant>(*I));
11162
11163 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011164 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011165 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011166
11167 // Replace all uses of the GEP with the new constexpr...
11168 return ReplaceInstUsesWith(GEP, CE);
11169 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011170 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011171 if (!isa<PointerType>(X->getType())) {
11172 // Not interesting. Source pointer must be a cast from pointer.
11173 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011174 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11175 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011176 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011177 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11178 // into : GEP i8* X, ...
11179 //
Chris Lattnereed48272005-09-13 00:40:14 +000011180 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011181 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11182 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011183 if (const ArrayType *CATy =
11184 dyn_cast<ArrayType>(CPTy->getElementType())) {
11185 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11186 if (CATy->getElementType() == XTy->getElementType()) {
11187 // -> GEP i8* X, ...
11188 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11189 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11190 GEP.getName());
11191 } else if (const ArrayType *XATy =
11192 dyn_cast<ArrayType>(XTy->getElementType())) {
11193 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011194 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011195 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011196 // At this point, we know that the cast source type is a pointer
11197 // to an array of the same type as the destination pointer
11198 // array. Because the array type is never stepped over (there
11199 // is a leading zero) we can fold the cast into this GEP.
11200 GEP.setOperand(0, X);
11201 return &GEP;
11202 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011203 }
11204 }
Chris Lattnereed48272005-09-13 00:40:14 +000011205 } else if (GEP.getNumOperands() == 2) {
11206 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011207 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11208 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011209 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11210 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011211 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011212 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11213 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011214 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011215 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011216 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011217 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011218 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011219 // V and GEP are both pointer types --> BitCast
11220 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011221 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011222
11223 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011224 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011225 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011226 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011227
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011228 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011229 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011230 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011231
11232 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11233 // allow either a mul, shift, or constant here.
11234 Value *NewIdx = 0;
11235 ConstantInt *Scale = 0;
11236 if (ArrayEltSize == 1) {
11237 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011238 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011239 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011240 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011241 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011242 Scale = CI;
11243 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11244 if (Inst->getOpcode() == Instruction::Shl &&
11245 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011246 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11247 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011248 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011249 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011250 NewIdx = Inst->getOperand(0);
11251 } else if (Inst->getOpcode() == Instruction::Mul &&
11252 isa<ConstantInt>(Inst->getOperand(1))) {
11253 Scale = cast<ConstantInt>(Inst->getOperand(1));
11254 NewIdx = Inst->getOperand(0);
11255 }
11256 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011257
Chris Lattner7835cdd2005-09-13 18:36:04 +000011258 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011259 // out, perform the transformation. Note, we don't know whether Scale is
11260 // signed or not. We'll use unsigned version of division/modulo
11261 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011262 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011263 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011264 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011265 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011266 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011267 Constant *C =
11268 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011269 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011270 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011271 NewIdx = InsertNewInstBefore(Sc, GEP);
11272 }
11273
11274 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011275 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011276 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011277 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011278 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011279 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011280 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11281 // The NewGEP must be pointer typed, so must the old one -> BitCast
11282 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011283 }
11284 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011285 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011286 }
Chris Lattner58407792009-01-09 04:53:57 +000011287
Chris Lattner46cd5a12009-01-09 05:44:56 +000011288 /// See if we can simplify:
11289 /// X = bitcast A to B*
11290 /// Y = gep X, <...constant indices...>
11291 /// into a gep of the original struct. This is important for SROA and alias
11292 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011293 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011294 if (TD &&
11295 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011296 // Determine how much the GEP moves the pointer. We are guaranteed to get
11297 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011298 ConstantInt *OffsetV =
11299 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011300 int64_t Offset = OffsetV->getSExtValue();
11301
11302 // If this GEP instruction doesn't move the pointer, just replace the GEP
11303 // with a bitcast of the real input to the dest type.
11304 if (Offset == 0) {
11305 // If the bitcast is of an allocation, and the allocation will be
11306 // converted to match the type of the cast, don't touch this.
11307 if (isa<AllocationInst>(BCI->getOperand(0))) {
11308 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11309 if (Instruction *I = visitBitCast(*BCI)) {
11310 if (I != BCI) {
11311 I->takeName(BCI);
11312 BCI->getParent()->getInstList().insert(BCI, I);
11313 ReplaceInstUsesWith(*BCI, I);
11314 }
11315 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011316 }
Chris Lattner58407792009-01-09 04:53:57 +000011317 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011318 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011319 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011320
11321 // Otherwise, if the offset is non-zero, we need to find out if there is a
11322 // field at Offset in 'A's type. If so, we can pull the cast through the
11323 // GEP.
11324 SmallVector<Value*, 8> NewIndices;
11325 const Type *InTy =
11326 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011327 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011328 Instruction *NGEP =
11329 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11330 NewIndices.end());
11331 if (NGEP->getType() == GEP.getType()) return NGEP;
11332 InsertNewInstBefore(NGEP, GEP);
11333 NGEP->takeName(&GEP);
11334 return new BitCastInst(NGEP, GEP.getType());
11335 }
Chris Lattner58407792009-01-09 04:53:57 +000011336 }
11337 }
11338
Chris Lattner8a2a3112001-12-14 16:52:21 +000011339 return 0;
11340}
11341
Chris Lattner0864acf2002-11-04 16:18:53 +000011342Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11343 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011344 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011345 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11346 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011347 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011348 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011349
11350 // Create and insert the replacement instruction...
11351 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011352 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011353 else {
11354 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011355 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011356 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011357
11358 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011359
Chris Lattner0864acf2002-11-04 16:18:53 +000011360 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011361 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011362 //
11363 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011364 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011365
11366 // Now that I is pointing to the first non-allocation-inst in the block,
11367 // insert our getelementptr instruction...
11368 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011369 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011370 Value *Idx[2];
11371 Idx[0] = NullIdx;
11372 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011373 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11374 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011375
11376 // Now make everything use the getelementptr instead of the original
11377 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011378 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011379 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011380 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011381 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011382 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011383
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011384 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011385 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011386 // Note that we only do this for alloca's, because malloc should allocate
11387 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011388 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011389 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011390
11391 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11392 if (AI.getAlignment() == 0)
11393 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11394 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011395
Chris Lattner0864acf2002-11-04 16:18:53 +000011396 return 0;
11397}
11398
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011399Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11400 Value *Op = FI.getOperand(0);
11401
Chris Lattner17be6352004-10-18 02:59:09 +000011402 // free undef -> unreachable.
11403 if (isa<UndefValue>(Op)) {
11404 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011405 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011406 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011407 return EraseInstFromFunction(FI);
11408 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011409
Chris Lattner6160e852004-02-28 04:57:37 +000011410 // If we have 'free null' delete the instruction. This can happen in stl code
11411 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011412 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011413 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011414
11415 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11416 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11417 FI.setOperand(0, CI->getOperand(0));
11418 return &FI;
11419 }
11420
11421 // Change free (gep X, 0,0,0,0) into free(X)
11422 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11423 if (GEPI->hasAllZeroIndices()) {
11424 AddToWorkList(GEPI);
11425 FI.setOperand(0, GEPI->getOperand(0));
11426 return &FI;
11427 }
11428 }
11429
11430 // Change free(malloc) into nothing, if the malloc has a single use.
11431 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11432 if (MI->hasOneUse()) {
11433 EraseInstFromFunction(FI);
11434 return EraseInstFromFunction(*MI);
11435 }
Chris Lattner6160e852004-02-28 04:57:37 +000011436
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011437 return 0;
11438}
11439
11440
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011441/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011442static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011443 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011444 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011445 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011446 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011447
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011448 if (TD) {
11449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11450 // Instead of loading constant c string, use corresponding integer value
11451 // directly if string length is small enough.
11452 std::string Str;
11453 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11454 unsigned len = Str.length();
11455 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11456 unsigned numBits = Ty->getPrimitiveSizeInBits();
11457 // Replace LI with immediate integer store.
11458 if ((numBits >> 3) == len + 1) {
11459 APInt StrVal(numBits, 0);
11460 APInt SingleChar(numBits, 0);
11461 if (TD->isLittleEndian()) {
11462 for (signed i = len-1; i >= 0; i--) {
11463 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11464 StrVal = (StrVal << 8) | SingleChar;
11465 }
11466 } else {
11467 for (unsigned i = 0; i < len; i++) {
11468 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11469 StrVal = (StrVal << 8) | SingleChar;
11470 }
11471 // Append NULL at the end.
11472 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011473 StrVal = (StrVal << 8) | SingleChar;
11474 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011475 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011476 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011477 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011478 }
11479 }
11480 }
11481
Mon P Wang6753f952009-02-07 22:19:29 +000011482 const PointerType *DestTy = cast<PointerType>(CI->getType());
11483 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011484 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011485
11486 // If the address spaces don't match, don't eliminate the cast.
11487 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11488 return 0;
11489
Chris Lattnerb89e0712004-07-13 01:49:43 +000011490 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011491
Reid Spencer42230162007-01-22 05:51:25 +000011492 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011493 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011494 // If the source is an array, the code below will not succeed. Check to
11495 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11496 // constants.
11497 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11498 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11499 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011500 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011501 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11502 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011503 SrcTy = cast<PointerType>(CastOp->getType());
11504 SrcPTy = SrcTy->getElementType();
11505 }
11506
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011507 if (IC.getTargetData() &&
11508 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011509 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011510 // Do not allow turning this into a load of an integer, which is then
11511 // casted to a pointer, this pessimizes pointer analysis a lot.
11512 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011513 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11514 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011515
Chris Lattnerf9527852005-01-31 04:50:46 +000011516 // Okay, we are casting from one integer or pointer type to another of
11517 // the same size. Instead of casting the pointer before the load, cast
11518 // the result of the loaded value.
11519 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11520 CI->getName(),
11521 LI.isVolatile()),LI);
11522 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011523 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011524 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011525 }
11526 }
11527 return 0;
11528}
11529
Chris Lattner833b8a42003-06-26 05:06:25 +000011530Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11531 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011532
Dan Gohman9941f742007-07-20 16:34:21 +000011533 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011534 if (TD) {
11535 unsigned KnownAlign =
11536 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11537 if (KnownAlign >
11538 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11539 LI.getAlignment()))
11540 LI.setAlignment(KnownAlign);
11541 }
Dan Gohman9941f742007-07-20 16:34:21 +000011542
Chris Lattner37366c12005-05-01 04:24:53 +000011543 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011544 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011545 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011546 return Res;
11547
11548 // None of the following transforms are legal for volatile loads.
11549 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011550
Dan Gohman2276a7b2008-10-15 23:19:35 +000011551 // Do really simple store-to-load forwarding and load CSE, to catch cases
11552 // where there are several consequtive memory accesses to the same location,
11553 // separated by a few arithmetic operations.
11554 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011555 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11556 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011557
Christopher Lambb15147e2007-12-29 07:56:53 +000011558 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11559 const Value *GEPI0 = GEPI->getOperand(0);
11560 // TODO: Consider a target hook for valid address spaces for this xform.
11561 if (isa<ConstantPointerNull>(GEPI0) &&
11562 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011563 // Insert a new store to null instruction before the load to indicate
11564 // that this code is not reachable. We do this instead of inserting
11565 // an unreachable instruction directly because we cannot modify the
11566 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011567 new StoreInst(Context->getUndef(LI.getType()),
11568 Context->getNullValue(Op->getType()), &LI);
11569 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011570 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011571 }
Chris Lattner37366c12005-05-01 04:24:53 +000011572
Chris Lattnere87597f2004-10-16 18:11:37 +000011573 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011574 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011575 // TODO: Consider a target hook for valid address spaces for this xform.
11576 if (isa<UndefValue>(C) || (C->isNullValue() &&
11577 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011578 // Insert a new store to null instruction before the load to indicate that
11579 // this code is not reachable. We do this instead of inserting an
11580 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011581 new StoreInst(Context->getUndef(LI.getType()),
11582 Context->getNullValue(Op->getType()), &LI);
11583 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011584 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011585
Chris Lattnere87597f2004-10-16 18:11:37 +000011586 // Instcombine load (constant global) into the value loaded.
11587 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011588 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011589 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011590
Chris Lattnere87597f2004-10-16 18:11:37 +000011591 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011592 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011593 if (CE->getOpcode() == Instruction::GetElementPtr) {
11594 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011595 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011596 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011597 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011598 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011599 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011600 if (CE->getOperand(0)->isNullValue()) {
11601 // Insert a new store to null instruction before the load to indicate
11602 // that this code is not reachable. We do this instead of inserting
11603 // an unreachable instruction directly because we cannot modify the
11604 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011605 new StoreInst(Context->getUndef(LI.getType()),
11606 Context->getNullValue(Op->getType()), &LI);
11607 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011608 }
11609
Reid Spencer3da59db2006-11-27 01:05:10 +000011610 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011611 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011612 return Res;
11613 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011614 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011615 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011616
11617 // If this load comes from anywhere in a constant global, and if the global
11618 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011619 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011620 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011621 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011622 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011623 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011624 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011625 }
11626 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011627
Chris Lattner37366c12005-05-01 04:24:53 +000011628 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011629 // Change select and PHI nodes to select values instead of addresses: this
11630 // helps alias analysis out a lot, allows many others simplifications, and
11631 // exposes redundancy in the code.
11632 //
11633 // Note that we cannot do the transformation unless we know that the
11634 // introduced loads cannot trap! Something like this is valid as long as
11635 // the condition is always false: load (select bool %C, int* null, int* %G),
11636 // but it would not be valid if we transformed it to load from null
11637 // unconditionally.
11638 //
11639 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11640 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011641 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11642 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011643 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011644 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011645 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011646 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011647 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011648 }
11649
Chris Lattner684fe212004-09-23 15:46:00 +000011650 // load (select (cond, null, P)) -> load P
11651 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11652 if (C->isNullValue()) {
11653 LI.setOperand(0, SI->getOperand(2));
11654 return &LI;
11655 }
11656
11657 // load (select (cond, P, null)) -> load P
11658 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11659 if (C->isNullValue()) {
11660 LI.setOperand(0, SI->getOperand(1));
11661 return &LI;
11662 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011663 }
11664 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011665 return 0;
11666}
11667
Reid Spencer55af2b52007-01-19 21:20:31 +000011668/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011669/// when possible. This makes it generally easy to do alias analysis and/or
11670/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011671static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11672 User *CI = cast<User>(SI.getOperand(1));
11673 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011674 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011675
11676 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011677 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11678 if (SrcTy == 0) return 0;
11679
11680 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011681
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011682 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11683 return 0;
11684
Chris Lattner3914f722009-01-24 01:00:13 +000011685 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11686 /// to its first element. This allows us to handle things like:
11687 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11688 /// on 32-bit hosts.
11689 SmallVector<Value*, 4> NewGEPIndices;
11690
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011691 // If the source is an array, the code below will not succeed. Check to
11692 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11693 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011694 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11695 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011696 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011697 NewGEPIndices.push_back(Zero);
11698
11699 while (1) {
11700 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011701 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011702 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011703 NewGEPIndices.push_back(Zero);
11704 SrcPTy = STy->getElementType(0);
11705 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11706 NewGEPIndices.push_back(Zero);
11707 SrcPTy = ATy->getElementType();
11708 } else {
11709 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011710 }
Chris Lattner3914f722009-01-24 01:00:13 +000011711 }
11712
Owen Andersond672ecb2009-07-03 00:17:18 +000011713 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011714 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011715
11716 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11717 return 0;
11718
Chris Lattner71759c42009-01-16 20:12:52 +000011719 // If the pointers point into different address spaces or if they point to
11720 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011721 if (!IC.getTargetData() ||
11722 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011723 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011724 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11725 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011726 return 0;
11727
11728 // Okay, we are casting from one integer or pointer type to another of
11729 // the same size. Instead of casting the pointer before
11730 // the store, cast the value to be stored.
11731 Value *NewCast;
11732 Value *SIOp0 = SI.getOperand(0);
11733 Instruction::CastOps opcode = Instruction::BitCast;
11734 const Type* CastSrcTy = SIOp0->getType();
11735 const Type* CastDstTy = SrcPTy;
11736 if (isa<PointerType>(CastDstTy)) {
11737 if (CastSrcTy->isInteger())
11738 opcode = Instruction::IntToPtr;
11739 } else if (isa<IntegerType>(CastDstTy)) {
11740 if (isa<PointerType>(SIOp0->getType()))
11741 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011742 }
Chris Lattner3914f722009-01-24 01:00:13 +000011743
11744 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11745 // emit a GEP to index into its first field.
11746 if (!NewGEPIndices.empty()) {
11747 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011748 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011749 NewGEPIndices.size());
11750 else
11751 CastOp = IC.InsertNewInstBefore(
11752 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11753 NewGEPIndices.end()), SI);
11754 }
11755
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011756 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011757 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011758 else
11759 NewCast = IC.InsertNewInstBefore(
11760 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11761 SI);
11762 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011763}
11764
Chris Lattner4aebaee2008-11-27 08:56:30 +000011765/// equivalentAddressValues - Test if A and B will obviously have the same
11766/// value. This includes recognizing that %t0 and %t1 will have the same
11767/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011768/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011769/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011770/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011771/// %t2 = load i32* %t1
11772///
11773static bool equivalentAddressValues(Value *A, Value *B) {
11774 // Test if the values are trivially equivalent.
11775 if (A == B) return true;
11776
11777 // Test if the values come form identical arithmetic instructions.
11778 if (isa<BinaryOperator>(A) ||
11779 isa<CastInst>(A) ||
11780 isa<PHINode>(A) ||
11781 isa<GetElementPtrInst>(A))
11782 if (Instruction *BI = dyn_cast<Instruction>(B))
11783 if (cast<Instruction>(A)->isIdenticalTo(BI))
11784 return true;
11785
11786 // Otherwise they may not be equivalent.
11787 return false;
11788}
11789
Dale Johannesen4945c652009-03-03 21:26:39 +000011790// If this instruction has two uses, one of which is a llvm.dbg.declare,
11791// return the llvm.dbg.declare.
11792DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11793 if (!V->hasNUses(2))
11794 return 0;
11795 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11796 UI != E; ++UI) {
11797 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11798 return DI;
11799 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11800 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11801 return DI;
11802 }
11803 }
11804 return 0;
11805}
11806
Chris Lattner2f503e62005-01-31 05:36:43 +000011807Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11808 Value *Val = SI.getOperand(0);
11809 Value *Ptr = SI.getOperand(1);
11810
11811 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011812 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011813 ++NumCombined;
11814 return 0;
11815 }
Chris Lattner836692d2007-01-15 06:51:56 +000011816
11817 // If the RHS is an alloca with a single use, zapify the store, making the
11818 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011819 // If the RHS is an alloca with a two uses, the other one being a
11820 // llvm.dbg.declare, zapify the store and the declare, making the
11821 // alloca dead. We must do this to prevent declare's from affecting
11822 // codegen.
11823 if (!SI.isVolatile()) {
11824 if (Ptr->hasOneUse()) {
11825 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011826 EraseInstFromFunction(SI);
11827 ++NumCombined;
11828 return 0;
11829 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011830 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11831 if (isa<AllocaInst>(GEP->getOperand(0))) {
11832 if (GEP->getOperand(0)->hasOneUse()) {
11833 EraseInstFromFunction(SI);
11834 ++NumCombined;
11835 return 0;
11836 }
11837 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11838 EraseInstFromFunction(*DI);
11839 EraseInstFromFunction(SI);
11840 ++NumCombined;
11841 return 0;
11842 }
11843 }
11844 }
11845 }
11846 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11847 EraseInstFromFunction(*DI);
11848 EraseInstFromFunction(SI);
11849 ++NumCombined;
11850 return 0;
11851 }
Chris Lattner836692d2007-01-15 06:51:56 +000011852 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011853
Dan Gohman9941f742007-07-20 16:34:21 +000011854 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011855 if (TD) {
11856 unsigned KnownAlign =
11857 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11858 if (KnownAlign >
11859 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11860 SI.getAlignment()))
11861 SI.setAlignment(KnownAlign);
11862 }
Dan Gohman9941f742007-07-20 16:34:21 +000011863
Dale Johannesenacb51a32009-03-03 01:43:03 +000011864 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011865 // stores to the same location, separated by a few arithmetic operations. This
11866 // situation often occurs with bitfield accesses.
11867 BasicBlock::iterator BBI = &SI;
11868 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11869 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011870 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011871 // Don't count debug info directives, lest they affect codegen,
11872 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11873 // It is necessary for correctness to skip those that feed into a
11874 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011875 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011876 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011877 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011878 continue;
11879 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011880
11881 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11882 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011883 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11884 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011885 ++NumDeadStore;
11886 ++BBI;
11887 EraseInstFromFunction(*PrevSI);
11888 continue;
11889 }
11890 break;
11891 }
11892
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011893 // If this is a load, we have to stop. However, if the loaded value is from
11894 // the pointer we're loading and is producing the pointer we're storing,
11895 // then *this* store is dead (X = load P; store X -> P).
11896 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011897 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11898 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011899 EraseInstFromFunction(SI);
11900 ++NumCombined;
11901 return 0;
11902 }
11903 // Otherwise, this is a load from some other location. Stores before it
11904 // may not be dead.
11905 break;
11906 }
11907
Chris Lattner9ca96412006-02-08 03:25:32 +000011908 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011909 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011910 break;
11911 }
11912
11913
11914 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011915
11916 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011917 if (isa<ConstantPointerNull>(Ptr) &&
11918 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011919 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011920 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011921 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011922 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011923 ++NumCombined;
11924 }
11925 return 0; // Do not modify these!
11926 }
11927
11928 // store undef, Ptr -> noop
11929 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011930 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011931 ++NumCombined;
11932 return 0;
11933 }
11934
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011935 // If the pointer destination is a cast, see if we can fold the cast into the
11936 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011937 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011938 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11939 return Res;
11940 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011941 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011942 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11943 return Res;
11944
Chris Lattner408902b2005-09-12 23:23:25 +000011945
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011946 // If this store is the last instruction in the basic block (possibly
11947 // excepting debug info instructions and the pointer bitcasts that feed
11948 // into them), and if the block ends with an unconditional branch, try
11949 // to move it to the successor block.
11950 BBI = &SI;
11951 do {
11952 ++BBI;
11953 } while (isa<DbgInfoIntrinsic>(BBI) ||
11954 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011955 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011956 if (BI->isUnconditional())
11957 if (SimplifyStoreAtEndOfBlock(SI))
11958 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011959
Chris Lattner2f503e62005-01-31 05:36:43 +000011960 return 0;
11961}
11962
Chris Lattner3284d1f2007-04-15 00:07:55 +000011963/// SimplifyStoreAtEndOfBlock - Turn things like:
11964/// if () { *P = v1; } else { *P = v2 }
11965/// into a phi node with a store in the successor.
11966///
Chris Lattner31755a02007-04-15 01:02:18 +000011967/// Simplify things like:
11968/// *P = v1; if () { *P = v2; }
11969/// into a phi node with a store in the successor.
11970///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011971bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11972 BasicBlock *StoreBB = SI.getParent();
11973
11974 // Check to see if the successor block has exactly two incoming edges. If
11975 // so, see if the other predecessor contains a store to the same location.
11976 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011977 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011978
11979 // Determine whether Dest has exactly two predecessors and, if so, compute
11980 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011981 pred_iterator PI = pred_begin(DestBB);
11982 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011983 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011984 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011985 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011986 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011987 return false;
11988
11989 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011990 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011992 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011993 }
Chris Lattner31755a02007-04-15 01:02:18 +000011994 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011996
11997 // Bail out if all the relevant blocks aren't distinct (this can happen,
11998 // for example, if SI is in an infinite loop)
11999 if (StoreBB == DestBB || OtherBB == DestBB)
12000 return false;
12001
Chris Lattner31755a02007-04-15 01:02:18 +000012002 // Verify that the other block ends in a branch and is not otherwise empty.
12003 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012004 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012005 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012006 return false;
12007
Chris Lattner31755a02007-04-15 01:02:18 +000012008 // If the other block ends in an unconditional branch, check for the 'if then
12009 // else' case. there is an instruction before the branch.
12010 StoreInst *OtherStore = 0;
12011 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012012 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012013 // Skip over debugging info.
12014 while (isa<DbgInfoIntrinsic>(BBI) ||
12015 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12016 if (BBI==OtherBB->begin())
12017 return false;
12018 --BBI;
12019 }
12020 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012021 OtherStore = dyn_cast<StoreInst>(BBI);
12022 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12023 return false;
12024 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012025 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012026 // destinations is StoreBB, then we have the if/then case.
12027 if (OtherBr->getSuccessor(0) != StoreBB &&
12028 OtherBr->getSuccessor(1) != StoreBB)
12029 return false;
12030
12031 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012032 // if/then triangle. See if there is a store to the same ptr as SI that
12033 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012034 for (;; --BBI) {
12035 // Check to see if we find the matching store.
12036 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12037 if (OtherStore->getOperand(1) != SI.getOperand(1))
12038 return false;
12039 break;
12040 }
Eli Friedman6903a242008-06-13 22:02:12 +000012041 // If we find something that may be using or overwriting the stored
12042 // value, or if we run out of instructions, we can't do the xform.
12043 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012044 BBI == OtherBB->begin())
12045 return false;
12046 }
12047
12048 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012049 // make sure nothing reads or overwrites the stored value in
12050 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012051 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12052 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012053 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012054 return false;
12055 }
12056 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012057
Chris Lattner31755a02007-04-15 01:02:18 +000012058 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012059 Value *MergedVal = OtherStore->getOperand(0);
12060 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012061 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012062 PN->reserveOperandSpace(2);
12063 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012064 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12065 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012066 }
12067
12068 // Advance to a place where it is safe to insert the new store and
12069 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012070 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012071 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12072 OtherStore->isVolatile()), *BBI);
12073
12074 // Nuke the old stores.
12075 EraseInstFromFunction(SI);
12076 EraseInstFromFunction(*OtherStore);
12077 ++NumCombined;
12078 return true;
12079}
12080
Chris Lattner2f503e62005-01-31 05:36:43 +000012081
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012082Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12083 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012084 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012085 BasicBlock *TrueDest;
12086 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012087 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012088 !isa<Constant>(X)) {
12089 // Swap Destinations and condition...
12090 BI.setCondition(X);
12091 BI.setSuccessor(0, FalseDest);
12092 BI.setSuccessor(1, TrueDest);
12093 return &BI;
12094 }
12095
Reid Spencere4d87aa2006-12-23 06:05:41 +000012096 // Cannonicalize fcmp_one -> fcmp_oeq
12097 FCmpInst::Predicate FPred; Value *Y;
12098 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012099 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012100 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12101 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12102 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012103 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012104 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012105 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012106 // Swap Destinations and condition...
12107 BI.setCondition(NewSCC);
12108 BI.setSuccessor(0, FalseDest);
12109 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012110 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012111 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012112 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012113 return &BI;
12114 }
12115
12116 // Cannonicalize icmp_ne -> icmp_eq
12117 ICmpInst::Predicate IPred;
12118 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012119 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012120 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12121 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12122 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12123 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012124 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012125 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012126 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012127 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012128 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012129 BI.setSuccessor(0, FalseDest);
12130 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012131 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012132 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012133 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012134 return &BI;
12135 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012136
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012137 return 0;
12138}
Chris Lattner0864acf2002-11-04 16:18:53 +000012139
Chris Lattner46238a62004-07-03 00:26:11 +000012140Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12141 Value *Cond = SI.getCondition();
12142 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12143 if (I->getOpcode() == Instruction::Add)
12144 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12145 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12146 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012147 SI.setOperand(i,
12148 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012149 AddRHS));
12150 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012151 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012152 return &SI;
12153 }
12154 }
12155 return 0;
12156}
12157
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012158Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012159 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012160
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012161 if (!EV.hasIndices())
12162 return ReplaceInstUsesWith(EV, Agg);
12163
12164 if (Constant *C = dyn_cast<Constant>(Agg)) {
12165 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012166 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012167
12168 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012169 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012170
12171 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12172 // Extract the element indexed by the first index out of the constant
12173 Value *V = C->getOperand(*EV.idx_begin());
12174 if (EV.getNumIndices() > 1)
12175 // Extract the remaining indices out of the constant indexed by the
12176 // first index
12177 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12178 else
12179 return ReplaceInstUsesWith(EV, V);
12180 }
12181 return 0; // Can't handle other constants
12182 }
12183 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12184 // We're extracting from an insertvalue instruction, compare the indices
12185 const unsigned *exti, *exte, *insi, *inse;
12186 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12187 exte = EV.idx_end(), inse = IV->idx_end();
12188 exti != exte && insi != inse;
12189 ++exti, ++insi) {
12190 if (*insi != *exti)
12191 // The insert and extract both reference distinctly different elements.
12192 // This means the extract is not influenced by the insert, and we can
12193 // replace the aggregate operand of the extract with the aggregate
12194 // operand of the insert. i.e., replace
12195 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12196 // %E = extractvalue { i32, { i32 } } %I, 0
12197 // with
12198 // %E = extractvalue { i32, { i32 } } %A, 0
12199 return ExtractValueInst::Create(IV->getAggregateOperand(),
12200 EV.idx_begin(), EV.idx_end());
12201 }
12202 if (exti == exte && insi == inse)
12203 // Both iterators are at the end: Index lists are identical. Replace
12204 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12205 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12206 // with "i32 42"
12207 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12208 if (exti == exte) {
12209 // The extract list is a prefix of the insert list. i.e. replace
12210 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12211 // %E = extractvalue { i32, { i32 } } %I, 1
12212 // with
12213 // %X = extractvalue { i32, { i32 } } %A, 1
12214 // %E = insertvalue { i32 } %X, i32 42, 0
12215 // by switching the order of the insert and extract (though the
12216 // insertvalue should be left in, since it may have other uses).
12217 Value *NewEV = InsertNewInstBefore(
12218 ExtractValueInst::Create(IV->getAggregateOperand(),
12219 EV.idx_begin(), EV.idx_end()),
12220 EV);
12221 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12222 insi, inse);
12223 }
12224 if (insi == inse)
12225 // The insert list is a prefix of the extract list
12226 // We can simply remove the common indices from the extract and make it
12227 // operate on the inserted value instead of the insertvalue result.
12228 // i.e., replace
12229 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12230 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12231 // with
12232 // %E extractvalue { i32 } { i32 42 }, 0
12233 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12234 exti, exte);
12235 }
12236 // Can't simplify extracts from other values. Note that nested extracts are
12237 // already simplified implicitely by the above (extract ( extract (insert) )
12238 // will be translated into extract ( insert ( extract ) ) first and then just
12239 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012240 return 0;
12241}
12242
Chris Lattner220b0cf2006-03-05 00:22:33 +000012243/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12244/// is to leave as a vector operation.
12245static bool CheapToScalarize(Value *V, bool isConstant) {
12246 if (isa<ConstantAggregateZero>(V))
12247 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012248 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012249 if (isConstant) return true;
12250 // If all elts are the same, we can extract.
12251 Constant *Op0 = C->getOperand(0);
12252 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12253 if (C->getOperand(i) != Op0)
12254 return false;
12255 return true;
12256 }
12257 Instruction *I = dyn_cast<Instruction>(V);
12258 if (!I) return false;
12259
12260 // Insert element gets simplified to the inserted element or is deleted if
12261 // this is constant idx extract element and its a constant idx insertelt.
12262 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12263 isa<ConstantInt>(I->getOperand(2)))
12264 return true;
12265 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12266 return true;
12267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12268 if (BO->hasOneUse() &&
12269 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12270 CheapToScalarize(BO->getOperand(1), isConstant)))
12271 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012272 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12273 if (CI->hasOneUse() &&
12274 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12275 CheapToScalarize(CI->getOperand(1), isConstant)))
12276 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012277
12278 return false;
12279}
12280
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012281/// Read and decode a shufflevector mask.
12282///
12283/// It turns undef elements into values that are larger than the number of
12284/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012285static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12286 unsigned NElts = SVI->getType()->getNumElements();
12287 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12288 return std::vector<unsigned>(NElts, 0);
12289 if (isa<UndefValue>(SVI->getOperand(2)))
12290 return std::vector<unsigned>(NElts, 2*NElts);
12291
12292 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012293 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012294 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12295 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012296 Result.push_back(NElts*2); // undef -> 8
12297 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012298 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012299 return Result;
12300}
12301
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012302/// FindScalarElement - Given a vector and an element number, see if the scalar
12303/// value is already around as a register, for example if it were inserted then
12304/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012305static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012306 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012307 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12308 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012309 unsigned Width = PTy->getNumElements();
12310 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012311 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012312
12313 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012314 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012315 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012316 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012317 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318 return CP->getOperand(EltNo);
12319 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12320 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012321 if (!isa<ConstantInt>(III->getOperand(2)))
12322 return 0;
12323 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012324
12325 // If this is an insert to the element we are looking for, return the
12326 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012327 if (EltNo == IIElt)
12328 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012329
12330 // Otherwise, the insertelement doesn't modify the value, recurse on its
12331 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012332 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012333 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012334 unsigned LHSWidth =
12335 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012336 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012337 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012338 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012339 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012340 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012341 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012343 }
12344
12345 // Otherwise, we don't know.
12346 return 0;
12347}
12348
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012349Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012350 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012351 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012352 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012353
Dan Gohman07a96762007-07-16 14:29:03 +000012354 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012355 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012356 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012357
Reid Spencer9d6565a2007-02-15 02:26:10 +000012358 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012359 // If vector val is constant with all elements the same, replace EI with
12360 // that element. When the elements are not identical, we cannot replace yet
12361 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012362 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012363 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012364 if (C->getOperand(i) != op0) {
12365 op0 = 0;
12366 break;
12367 }
12368 if (op0)
12369 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012370 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012371
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012372 // If extracting a specified index from the vector, see if we can recursively
12373 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012374 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012375 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012376 unsigned VectorWidth =
12377 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012378
12379 // If this is extracting an invalid index, turn this into undef, to avoid
12380 // crashing the code below.
12381 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012382 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012383
Chris Lattner867b99f2006-10-05 06:55:50 +000012384 // This instruction only demands the single element from the input vector.
12385 // If the input vector has a single use, simplify it based on this use
12386 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012387 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012388 APInt UndefElts(VectorWidth, 0);
12389 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012390 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012391 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012392 EI.setOperand(0, V);
12393 return &EI;
12394 }
12395 }
12396
Owen Andersond672ecb2009-07-03 00:17:18 +000012397 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012398 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012399
12400 // If the this extractelement is directly using a bitcast from a vector of
12401 // the same number of elements, see if we can find the source element from
12402 // it. In this case, we will end up needing to bitcast the scalars.
12403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12404 if (const VectorType *VT =
12405 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12406 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012407 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12408 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012409 return new BitCastInst(Elt, EI.getType());
12410 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012411 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012412
Chris Lattner73fa49d2006-05-25 22:53:38 +000012413 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012414 if (I->hasOneUse()) {
12415 // Push extractelement into predecessor operation if legal and
12416 // profitable to do so
12417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012418 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12419 if (CheapToScalarize(BO, isConstantElt)) {
12420 ExtractElementInst *newEI0 =
12421 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12422 EI.getName()+".lhs");
12423 ExtractElementInst *newEI1 =
12424 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12425 EI.getName()+".rhs");
12426 InsertNewInstBefore(newEI0, EI);
12427 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012428 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012429 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012430 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012431 unsigned AS =
12432 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012433 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012434 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012435 GetElementPtrInst *GEP =
12436 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012437 InsertNewInstBefore(GEP, EI);
12438 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012439 }
12440 }
12441 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12442 // Extracting the inserted element?
12443 if (IE->getOperand(2) == EI.getOperand(1))
12444 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12445 // If the inserted and extracted elements are constants, they must not
12446 // be the same value, extract from the pre-inserted value instead.
12447 if (isa<Constant>(IE->getOperand(2)) &&
12448 isa<Constant>(EI.getOperand(1))) {
12449 AddUsesToWorkList(EI);
12450 EI.setOperand(0, IE->getOperand(0));
12451 return &EI;
12452 }
12453 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12454 // If this is extracting an element from a shufflevector, figure out where
12455 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012456 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12457 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012458 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012459 unsigned LHSWidth =
12460 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12461
12462 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012463 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012464 else if (SrcIdx < LHSWidth*2) {
12465 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 Src = SVI->getOperand(1);
12467 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012468 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012469 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012470 return new ExtractElementInst(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +000012471 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012472 }
12473 }
Eli Friedman2451a642009-07-18 23:06:53 +000012474 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012475 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012476 return 0;
12477}
12478
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012479/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12480/// elements from either LHS or RHS, return the shuffle mask and true.
12481/// Otherwise, return false.
12482static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012483 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012484 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012485 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12486 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012487 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012488
12489 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012490 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012491 return true;
12492 } else if (V == LHS) {
12493 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012494 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012495 return true;
12496 } else if (V == RHS) {
12497 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012498 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499 return true;
12500 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12501 // If this is an insert of an extract from some other vector, include it.
12502 Value *VecOp = IEI->getOperand(0);
12503 Value *ScalarOp = IEI->getOperand(1);
12504 Value *IdxOp = IEI->getOperand(2);
12505
Chris Lattnerd929f062006-04-27 21:14:21 +000012506 if (!isa<ConstantInt>(IdxOp))
12507 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012508 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012509
12510 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12511 // Okay, we can handle this if the vector we are insertinting into is
12512 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012513 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012514 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012515 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012516 return true;
12517 }
12518 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12519 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012520 EI->getOperand(0)->getType() == V->getType()) {
12521 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012522 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012523
12524 // This must be extracting from either LHS or RHS.
12525 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
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 Lattner7f6cc0c2006-04-16 00:51:47 +000012529 // If so, update the mask to reflect the inserted value.
12530 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012531 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012532 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012533 } else {
12534 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012535 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012536 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012537
12538 }
12539 return true;
12540 }
12541 }
12542 }
12543 }
12544 }
12545 // TODO: Handle shufflevector here!
12546
12547 return false;
12548}
12549
12550/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12551/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12552/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012553static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012554 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012555 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012556 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012557 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012558 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012559
12560 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012561 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012562 return V;
12563 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012564 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012565 return V;
12566 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12567 // If this is an insert of an extract from some other vector, include it.
12568 Value *VecOp = IEI->getOperand(0);
12569 Value *ScalarOp = IEI->getOperand(1);
12570 Value *IdxOp = IEI->getOperand(2);
12571
12572 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12573 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12574 EI->getOperand(0)->getType() == V->getType()) {
12575 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012576 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12577 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012578
12579 // Either the extracted from or inserted into vector must be RHSVec,
12580 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012581 if (EI->getOperand(0) == RHS || RHS == 0) {
12582 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012583 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012584 Mask[InsertedIdx % NumElts] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012585 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012586 return V;
12587 }
12588
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012589 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012590 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12591 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012592 // Everything but the extracted element is replaced with the RHS.
12593 for (unsigned i = 0; i != NumElts; ++i) {
12594 if (i != InsertedIdx)
Owen Andersoneed707b2009-07-24 23:12:02 +000012595 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012596 }
12597 return V;
12598 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012599
12600 // If this insertelement is a chain that comes from exactly these two
12601 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012602 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12603 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012604 return EI->getOperand(0);
12605
Chris Lattnerefb47352006-04-15 01:39:45 +000012606 }
12607 }
12608 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012609 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012610
12611 // Otherwise, can't do anything fancy. Return an identity vector.
12612 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +000012613 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012614 return V;
12615}
12616
12617Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12618 Value *VecOp = IE.getOperand(0);
12619 Value *ScalarOp = IE.getOperand(1);
12620 Value *IdxOp = IE.getOperand(2);
12621
Chris Lattner599ded12007-04-09 01:11:16 +000012622 // Inserting an undef or into an undefined place, remove this.
12623 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12624 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012625
Chris Lattnerefb47352006-04-15 01:39:45 +000012626 // If the inserted element was extracted from some other vector, and if the
12627 // indexes are constant, try to turn this into a shufflevector operation.
12628 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12629 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12630 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012631 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012632 unsigned ExtractedIdx =
12633 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012634 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012635
12636 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12637 return ReplaceInstUsesWith(IE, VecOp);
12638
12639 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012640 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012641
12642 // If we are extracting a value from a vector, then inserting it right
12643 // back into the same place, just use the input vector.
12644 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12645 return ReplaceInstUsesWith(IE, VecOp);
12646
12647 // We could theoretically do this for ANY input. However, doing so could
12648 // turn chains of insertelement instructions into a chain of shufflevector
12649 // instructions, and right now we do not merge shufflevectors. As such,
12650 // only do this in a situation where it is clear that there is benefit.
12651 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12652 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12653 // the values of VecOp, except then one read from EIOp0.
12654 // Build a new shuffle mask.
12655 std::vector<Constant*> Mask;
12656 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012657 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012658 else {
12659 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneed707b2009-07-24 23:12:02 +000012660 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012661 NumVectorElts));
12662 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012663 Mask[InsertedIdx] =
Owen Andersoneed707b2009-07-24 23:12:02 +000012664 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012665 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012666 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012667 }
12668
12669 // If this insertelement isn't used by some other insertelement, turn it
12670 // (and any insertelements it points to), into one big shuffle.
12671 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12672 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012673 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012674 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12675 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012676 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012677 return new ShuffleVectorInst(LHS, RHS,
12678 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012679 }
12680 }
12681 }
12682
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012683 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12684 APInt UndefElts(VWidth, 0);
12685 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12686 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12687 return &IE;
12688
Chris Lattnerefb47352006-04-15 01:39:45 +000012689 return 0;
12690}
12691
12692
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012693Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12694 Value *LHS = SVI.getOperand(0);
12695 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012696 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012697
12698 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012699
Chris Lattner867b99f2006-10-05 06:55:50 +000012700 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012701 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012702 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012703
Dan Gohman488fbfc2008-09-09 18:11:14 +000012704 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012705
12706 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12707 return 0;
12708
Evan Cheng388df622009-02-03 10:05:09 +000012709 APInt UndefElts(VWidth, 0);
12710 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12711 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012712 LHS = SVI.getOperand(0);
12713 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012714 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012715 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012716
Chris Lattner863bcff2006-05-25 23:48:38 +000012717 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12718 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12719 if (LHS == RHS || isa<UndefValue>(LHS)) {
12720 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012721 // shuffle(undef,undef,mask) -> undef.
12722 return ReplaceInstUsesWith(SVI, LHS);
12723 }
12724
Chris Lattner863bcff2006-05-25 23:48:38 +000012725 // Remap any references to RHS to use LHS.
12726 std::vector<Constant*> Elts;
12727 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012728 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012729 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012730 else {
12731 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012732 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012733 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012734 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012735 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012736 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneed707b2009-07-24 23:12:02 +000012737 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012738 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012739 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012740 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012741 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012742 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12743 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012744 LHS = SVI.getOperand(0);
12745 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012746 MadeChange = true;
12747 }
12748
Chris Lattner7b2e27922006-05-26 00:29:06 +000012749 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012750 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012751
Chris Lattner863bcff2006-05-25 23:48:38 +000012752 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12753 if (Mask[i] >= e*2) continue; // Ignore undef values.
12754 // Is this an identity shuffle of the LHS value?
12755 isLHSID &= (Mask[i] == i);
12756
12757 // Is this an identity shuffle of the RHS value?
12758 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012759 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012760
Chris Lattner863bcff2006-05-25 23:48:38 +000012761 // Eliminate identity shuffles.
12762 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12763 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012764
Chris Lattner7b2e27922006-05-26 00:29:06 +000012765 // If the LHS is a shufflevector itself, see if we can combine it with this
12766 // one without producing an unusual shuffle. Here we are really conservative:
12767 // we are absolutely afraid of producing a shuffle mask not in the input
12768 // program, because the code gen may not be smart enough to turn a merged
12769 // shuffle into two specific shuffles: it may produce worse code. As such,
12770 // we only merge two shuffles if the result is one of the two input shuffle
12771 // masks. In this case, merging the shuffles just removes one instruction,
12772 // which we know is safe. This is good for things like turning:
12773 // (splat(splat)) -> splat.
12774 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12775 if (isa<UndefValue>(RHS)) {
12776 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12777
12778 std::vector<unsigned> NewMask;
12779 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12780 if (Mask[i] >= 2*e)
12781 NewMask.push_back(2*e);
12782 else
12783 NewMask.push_back(LHSMask[Mask[i]]);
12784
12785 // If the result mask is equal to the src shuffle or this shuffle mask, do
12786 // the replacement.
12787 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012788 unsigned LHSInNElts =
12789 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012790 std::vector<Constant*> Elts;
12791 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012792 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012793 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012794 } else {
Owen Andersoneed707b2009-07-24 23:12:02 +000012795 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012796 }
12797 }
12798 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12799 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012800 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012801 }
12802 }
12803 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012804
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012805 return MadeChange ? &SVI : 0;
12806}
12807
12808
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012809
Chris Lattnerea1c4542004-12-08 23:43:58 +000012810
12811/// TryToSinkInstruction - Try to move the specified instruction from its
12812/// current block into the beginning of DestBlock, which can only happen if it's
12813/// safe to move the instruction past all of the instructions between it and the
12814/// end of its block.
12815static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12816 assert(I->hasOneUse() && "Invariants didn't hold!");
12817
Chris Lattner108e9022005-10-27 17:13:11 +000012818 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012819 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012820 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012821
Chris Lattnerea1c4542004-12-08 23:43:58 +000012822 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012823 if (isa<AllocaInst>(I) && I->getParent() ==
12824 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012825 return false;
12826
Chris Lattner96a52a62004-12-09 07:14:34 +000012827 // We can only sink load instructions if there is nothing between the load and
12828 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012829 if (I->mayReadFromMemory()) {
12830 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012831 Scan != E; ++Scan)
12832 if (Scan->mayWriteToMemory())
12833 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012834 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012835
Dan Gohman02dea8b2008-05-23 21:05:58 +000012836 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012837
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012838 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012839 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012840 ++NumSunkInst;
12841 return true;
12842}
12843
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012844
12845/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12846/// all reachable code to the worklist.
12847///
12848/// This has a couple of tricks to make the code faster and more powerful. In
12849/// particular, we constant fold and DCE instructions as we go, to avoid adding
12850/// them to the worklist (this significantly speeds up instcombine on code where
12851/// many instructions are dead or constant). Additionally, if we find a branch
12852/// whose condition is a known constant, we only visit the reachable successors.
12853///
12854static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012855 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012856 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012857 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012858 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012859 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012860
Chris Lattner2c7718a2007-03-23 19:17:18 +000012861 while (!Worklist.empty()) {
12862 BB = Worklist.back();
12863 Worklist.pop_back();
12864
12865 // We have now visited this block! If we've already been here, ignore it.
12866 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012867
12868 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012869 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12870 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012871
Chris Lattner2c7718a2007-03-23 19:17:18 +000012872 // DCE instruction if trivially dead.
12873 if (isInstructionTriviallyDead(Inst)) {
12874 ++NumDeadInst;
12875 DOUT << "IC: DCE: " << *Inst;
12876 Inst->eraseFromParent();
12877 continue;
12878 }
12879
12880 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012881 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012882 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12883 Inst->replaceAllUsesWith(C);
12884 ++NumConstProp;
12885 Inst->eraseFromParent();
12886 continue;
12887 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012888
Devang Patel7fe1dec2008-11-19 18:56:50 +000012889 // If there are two consecutive llvm.dbg.stoppoint calls then
12890 // it is likely that the optimizer deleted code in between these
12891 // two intrinsics.
12892 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12893 if (DBI_Next) {
12894 if (DBI_Prev
12895 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12896 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12897 IC.RemoveFromWorkList(DBI_Prev);
12898 DBI_Prev->eraseFromParent();
12899 }
12900 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012901 } else {
12902 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012903 }
12904
Chris Lattner2c7718a2007-03-23 19:17:18 +000012905 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012906 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012907
12908 // Recursively visit successors. If this is a branch or switch on a
12909 // constant, only visit the reachable successor.
12910 TerminatorInst *TI = BB->getTerminator();
12911 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12912 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12913 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012914 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012915 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012916 continue;
12917 }
12918 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12919 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12920 // See if this is an explicit destination.
12921 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12922 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012923 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012924 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012925 continue;
12926 }
12927
12928 // Otherwise it is the default destination.
12929 Worklist.push_back(SI->getSuccessor(0));
12930 continue;
12931 }
12932 }
12933
12934 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12935 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012936 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012937}
12938
Chris Lattnerec9c3582007-03-03 02:04:50 +000012939bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012940 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012941 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012942
12943 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12944 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012945
Chris Lattnerb3d59702005-07-07 20:40:38 +000012946 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012947 // Do a depth-first traversal of the function, populate the worklist with
12948 // the reachable instructions. Ignore blocks that are not reachable. Keep
12949 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012950 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012951 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012952
Chris Lattnerb3d59702005-07-07 20:40:38 +000012953 // Do a quick scan over the function. If we find any blocks that are
12954 // unreachable, remove any instructions inside of them. This prevents
12955 // the instcombine code from having to deal with some bad special cases.
12956 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12957 if (!Visited.count(BB)) {
12958 Instruction *Term = BB->getTerminator();
12959 while (Term != BB->begin()) { // Remove instrs bottom-up
12960 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012961
Bill Wendlingb7427032006-11-26 09:46:52 +000012962 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012963 // A debug intrinsic shouldn't force another iteration if we weren't
12964 // going to do one without it.
12965 if (!isa<DbgInfoIntrinsic>(I)) {
12966 ++NumDeadInst;
12967 Changed = true;
12968 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012969 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012970 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012971 I->eraseFromParent();
12972 }
12973 }
12974 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012975
Chris Lattnerdbab3862007-03-02 21:28:56 +000012976 while (!Worklist.empty()) {
12977 Instruction *I = RemoveOneFromWorkList();
12978 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012979
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012980 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012981 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012982 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012983 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012984 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012985 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012986
Bill Wendlingb7427032006-11-26 09:46:52 +000012987 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012988
12989 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012990 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012991 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012992 continue;
12993 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012994
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012995 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012996 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012997 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012998
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012999 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013000 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013001 ReplaceInstUsesWith(*I, C);
13002
Chris Lattner62b14df2002-09-02 04:59:56 +000013003 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013004 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;
Chris Lattner62b14df2002-09-02 04:59:56 +000013008 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013009
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013010 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013011 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013012 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13013 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013014 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13015 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013016 if (NewC != CE) {
13017 i->set(NewC);
13018 Changed = true;
13019 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013020 }
13021
Chris Lattnerea1c4542004-12-08 23:43:58 +000013022 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013023 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013024 BasicBlock *BB = I->getParent();
13025 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13026 if (UserParent != BB) {
13027 bool UserIsSuccessor = false;
13028 // See if the user is one of our successors.
13029 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13030 if (*SI == UserParent) {
13031 UserIsSuccessor = true;
13032 break;
13033 }
13034
13035 // If the user is one of our immediate successors, and if that successor
13036 // only has us as a predecessors (we'd have to split the critical edge
13037 // otherwise), we can keep going.
13038 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13039 next(pred_begin(UserParent)) == pred_end(UserParent))
13040 // Okay, the CFG is simple enough, try to sink this instruction.
13041 Changed |= TryToSinkInstruction(I, UserParent);
13042 }
13043 }
13044
Chris Lattner8a2a3112001-12-14 16:52:21 +000013045 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013046#ifndef NDEBUG
13047 std::string OrigI;
13048#endif
13049 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013050 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013051 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013052 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013053 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013054 DOUT << "IC: Old = " << *I
13055 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013056
Chris Lattnerf523d062004-06-09 05:08:07 +000013057 // Everything uses the new instruction now.
13058 I->replaceAllUsesWith(Result);
13059
13060 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013061 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013062 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013063
Chris Lattner6934a042007-02-11 01:23:03 +000013064 // Move the name to the new instruction first.
13065 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013066
13067 // Insert the new instruction into the basic block...
13068 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013069 BasicBlock::iterator InsertPos = I;
13070
13071 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13072 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13073 ++InsertPos;
13074
13075 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013076
Chris Lattner00d51312004-05-01 23:27:23 +000013077 // Make sure that we reprocess all operands now that we reduced their
13078 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013079 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013080
Chris Lattnerf523d062004-06-09 05:08:07 +000013081 // Instructions can end up on the worklist more than once. Make sure
13082 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013083 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013084
13085 // Erase the old instruction.
13086 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013087 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013088#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013089 DOUT << "IC: Mod = " << OrigI
13090 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013091#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013092
Chris Lattner90ac28c2002-08-02 19:29:35 +000013093 // If the instruction was modified, it's possible that it is now dead.
13094 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013095 if (isInstructionTriviallyDead(I)) {
13096 // Make sure we process all operands now that we are reducing their
13097 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013098 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013099
Chris Lattner00d51312004-05-01 23:27:23 +000013100 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013101 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013102 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013103 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013104 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013105 AddToWorkList(I);
13106 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013107 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013109 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013110 }
13111 }
13112
Chris Lattnerec9c3582007-03-03 02:04:50 +000013113 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013114
13115 // Do an explicit clear, this shrinks the map if needed.
13116 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013117 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013118}
13119
Chris Lattnerec9c3582007-03-03 02:04:50 +000013120
13121bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013122 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013123 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013124
Chris Lattnerec9c3582007-03-03 02:04:50 +000013125 bool EverMadeChange = false;
13126
13127 // Iterate while there is work to do.
13128 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013129 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013130 EverMadeChange = true;
13131 return EverMadeChange;
13132}
13133
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013134FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013135 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013136}