blob: 01fa68b2f08f592342ae861c77128013b2b6b64e [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 Lattner7e708292002-06-25 16:13:24 +0000192 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000193 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000195 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000196 Instruction *visitOr (BinaryOperator &I);
197 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000198 Instruction *visitShl(BinaryOperator &I);
199 Instruction *visitAShr(BinaryOperator &I);
200 Instruction *visitLShr(BinaryOperator &I);
201 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000202 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208 Instruction *LHS,
209 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000210 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000212
Reid Spencere4d87aa2006-12-23 06:05:41 +0000213 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000215 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000216 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000217 Instruction *commonCastTransforms(CastInst &CI);
218 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000220 Instruction *visitTrunc(TruncInst &CI);
221 Instruction *visitZExt(ZExtInst &CI);
222 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000223 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000224 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000225 Instruction *visitFPToUI(FPToUIInst &FI);
226 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitUIToFP(CastInst &CI);
228 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000229 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000230 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000231 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000232 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000234 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000235 Instruction *visitSelectInst(SelectInst &SI);
236 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 Instruction *visitCallInst(CallInst &CI);
238 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitPHINode(PHINode &PN);
240 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000241 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000242 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000243 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000244 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000245 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000246 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000247 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000248 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000249 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000250 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251
252 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000254
Chris Lattner9fe38862003-06-19 17:00:31 +0000255 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000256 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000257 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000258 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000259 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000261 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000262 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
Chris Lattner9fe38862003-06-19 17:00:31 +0000264
Chris Lattner28977af2004-04-05 01:30:19 +0000265 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000266 // InsertNewInstBefore - insert an instruction New before instruction Old
267 // in the program. Add the new instruction to the worklist.
268 //
Chris Lattner955f3312004-09-28 21:48:02 +0000269 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000270 assert(New && New->getParent() == 0 &&
271 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000272 BasicBlock *BB = Old.getParent();
273 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000274 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000275 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279 /// This also adds the cast to the worklist. Finally, this returns the
280 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000281 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000283 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000284
Chris Lattnere2ed0572006-04-06 19:19:17 +0000285 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000286 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000287
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000288 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000290 return C;
291 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000292
293 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295 }
296
Chris Lattner0c967662004-09-24 15:21:34 +0000297
Chris Lattner8b170942002-08-09 23:47:40 +0000298 // ReplaceInstUsesWith - This method is to be used when an instruction is
299 // found to be dead, replacable with another preexisting expression. Here
300 // we add all uses of I to the worklist, replace all uses of I with the new
301 // value, then return I, so that the inst combiner will know that I was
302 // modified.
303 //
304 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000306 if (&I != V) {
307 I.replaceAllUsesWith(V);
308 return &I;
309 } else {
310 // If we are replacing the instruction with itself, this must be in a
311 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000312 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000313 return &I;
314 }
Chris Lattner8b170942002-08-09 23:47:40 +0000315 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343
Reid Spencere4d87aa2006-12-23 06:05:41 +0000344 /// SimplifyCommutative - This performs a few simplifications for
345 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000347
Reid Spencere4d87aa2006-12-23 06:05:41 +0000348 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349 /// most-complex to least-complex order.
350 bool SimplifyCompare(CmpInst &I);
351
Chris Lattner886ab6c2009-01-31 08:15:18 +0000352 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353 /// based on the demanded bits.
354 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
355 APInt& KnownZero, APInt& KnownOne,
356 unsigned Depth);
357 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000358 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000359 unsigned Depth=0);
360
361 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362 /// SimplifyDemandedBits knows about. See if the instruction has any
363 /// properties that allow us to simplify its operands.
364 bool SimplifyDemandedInstructionBits(Instruction &Inst);
365
Evan Cheng388df622009-02-03 10:05:09 +0000366 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000379 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
Chris Lattner7da52b22006-11-01 04:51:18 +0000381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394
Chris Lattnerafe91a52006-06-15 19:07:26 +0000395
Reid Spencerc55b2432006-12-13 18:21:21 +0000396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397
Dan Gohman6de29f82009-06-15 22:12:54 +0000398 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000399 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000412static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000414 if (BinaryOperator::isNeg(V) ||
415 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000416 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 return 3;
418 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000423
Chris Lattnerc8802d22003-03-11 00:12:48 +0000424// isOnlyUse - Return true if this instruction will be deleted if we stop using
425// it.
426static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000427 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000428}
429
Chris Lattner4cb170c2004-02-23 06:38:22 +0000430// getPromotedType - Return the specified type promoted as it would be to pass
431// though a va_arg area...
432static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000436 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000437 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000438}
439
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440/// getBitCastOperand - If the specified operand is a CastInst, a constant
441/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000443static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000444 if (Operator *O = dyn_cast<Operator>(V)) {
445 if (O->getOpcode() == Instruction::BitCast)
446 return O->getOperand(0);
447 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448 if (GEP->hasAllZeroIndices())
449 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000450 }
Chris Lattnereed48272005-09-13 00:40:14 +0000451 return 0;
452}
453
Reid Spencer3da59db2006-11-27 01:05:10 +0000454/// This function is a wrapper around CastInst::isEliminableCastPair. It
455/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000456static Instruction::CastOps
457isEliminableCastPair(
458 const CastInst *CI, ///< The first cast instruction
459 unsigned opcode, ///< The opcode of the second cast instruction
460 const Type *DstTy, ///< The target type for the second cast instruction
461 TargetData *TD ///< The target data for pointer size
462) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000463
Reid Spencer3da59db2006-11-27 01:05:10 +0000464 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
465 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 // Get the opcodes of the two Cast instructions
468 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Chris Lattnera0e69692009-03-24 18:35:40 +0000471 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000472 DstTy,
473 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000474
475 // We don't want to form an inttoptr or ptrtoint that converts to an integer
476 // type that differs from the pointer size.
477 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
478 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
479 Res = 0;
480
481 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000482}
483
484/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
485/// in any code being generated. It does not require codegen if V is simple
486/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000487static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
488 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000489 if (V->getType() == Ty || isa<Constant>(V)) return false;
490
Chris Lattner01575b72006-05-25 23:24:33 +0000491 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000492 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000493 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000494 return false;
495 return true;
496}
497
Chris Lattner4f98c562003-03-10 21:43:22 +0000498// SimplifyCommutative - This performs a few simplifications for commutative
499// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000500//
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// 1. Order operands such that they are listed from right (least complex) to
502// left (most complex). This puts constants before unary operators before
503// binary operators.
504//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000510 if (getComplexity(Context, I.getOperand(0)) <
511 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000519 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
524 return true;
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000532 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 Op1->getOperand(0),
535 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000536 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
539 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000543}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000544
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545/// SimplifyCompare - For a CmpInst this function just orders the operands
546/// so that theyare listed from right (least complex) to left (most complex).
547/// This puts constants before unary operators before binary operators.
548bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000549 if (getComplexity(Context, I.getOperand(0)) >=
550 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000551 return false;
552 I.swapOperands();
553 // Compare instructions are not associative so there's nothing else we can do.
554 return true;
555}
556
Chris Lattner8d969642003-03-10 23:06:50 +0000557// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000560static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000561 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000562 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000563
Chris Lattner0ce85802004-12-14 20:08:06 +0000564 // Constants can be considered to be negated values if they can be folded.
565 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000566 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000567
568 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000570 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000571
Chris Lattner8d969642003-03-10 23:06:50 +0000572 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000573}
574
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000575// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
576// instruction if the LHS is a constant negative zero (which is the 'negate'
577// form).
578//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000579static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000580 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000581 return BinaryOperator::getFNegArgument(V);
582
583 // Constants can be considered to be negated values if they can be folded.
584 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000585 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000586
587 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
588 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000589 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000590
591 return 0;
592}
593
Owen Anderson07cf79e2009-07-06 23:00:19 +0000594static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000595 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000596 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000597
598 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000599 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000600 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000601 return 0;
602}
603
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604// dyn_castFoldableMul - If this value is a multiply that can be folded into
605// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000606// non-constant operand of the multiply, and set CST to point to the multiplier.
607// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000608//
Owen Andersond672ecb2009-07-03 00:17:18 +0000609static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000610 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000611 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000612 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000613 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000614 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000616 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000617 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000618 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000619 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000620 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000621 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000622 return I->getOperand(0);
623 }
624 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000625 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000626}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000627
Chris Lattner574da9b2005-01-13 20:14:25 +0000628/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
629/// expression, return it.
630static User *dyn_castGetElementPtr(Value *V) {
631 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
633 if (CE->getOpcode() == Instruction::GetElementPtr)
634 return cast<User>(V);
635 return false;
636}
637
Reid Spencer7177c3a2007-03-25 05:33:51 +0000638/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000639static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000640 return Context->getConstantExprAdd(C,
641 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000642}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000643/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000644static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000645 return Context->getConstantExprSub(C,
646 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000647}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000648/// MultiplyOverflows - True if the multiply can not be expressed in an int
649/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000650static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000651 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 if (sign) {
655 LHSExt.sext(W * 2);
656 RHSExt.sext(W * 2);
657 } else {
658 LHSExt.zext(W * 2);
659 RHSExt.zext(W * 2);
660 }
661
662 APInt MulExt = LHSExt * RHSExt;
663
664 if (sign) {
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
668 } else
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670}
Chris Lattner955f3312004-09-28 21:48:02 +0000671
Reid Spencere7816b52007-03-08 01:52:58 +0000672
Chris Lattner255d8912006-02-11 09:31:47 +0000673/// ShrinkDemandedConstant - Check to see if the specified operand of the
674/// specified instruction is a constant integer. If so, check to see if there
675/// are any bits set in the constant that are not demanded. If so, shrink the
676/// constant and return true.
677static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000678 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
685
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
689 return false;
690
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000693 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000694 return true;
695}
696
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000697// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698// set of known zero and one bits, compute the maximum and minimum values that
699// could have the specified known zero and known one bits, returning them in
700// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000701static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000702 const APInt& KnownOne,
703 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000704 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
705 KnownZero.getBitWidth() == Min.getBitWidth() &&
706 KnownZero.getBitWidth() == Max.getBitWidth() &&
707 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000708 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000709
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
711 // bit if it is unknown.
712 Min = KnownOne;
713 Max = KnownOne|UnknownBits;
714
Dan Gohman1c8491e2009-04-25 17:12:48 +0000715 if (UnknownBits.isNegative()) { // Sign bit is unknown
716 Min.set(Min.getBitWidth()-1);
717 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719}
720
721// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
722// a set of known zero and one bits, compute the maximum and minimum values that
723// could have the specified known zero and known one bits, returning them in
724// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000725static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000726 const APInt &KnownOne,
727 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
729 KnownZero.getBitWidth() == Min.getBitWidth() &&
730 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000731 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000732 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000733
734 // The minimum value is when the unknown bits are all zeros.
735 Min = KnownOne;
736 // The maximum value is when the unknown bits are all ones.
737 Max = KnownOne|UnknownBits;
738}
Chris Lattner255d8912006-02-11 09:31:47 +0000739
Chris Lattner886ab6c2009-01-31 08:15:18 +0000740/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
741/// SimplifyDemandedBits knows about. See if the instruction has any
742/// properties that allow us to simplify its operands.
743bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000744 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000745 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
746 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
747
748 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
749 KnownZero, KnownOne, 0);
750 if (V == 0) return false;
751 if (V == &Inst) return true;
752 ReplaceInstUsesWith(Inst, V);
753 return true;
754}
755
756/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
757/// specified instruction operand if possible, updating it in place. It returns
758/// true if it made any change and false otherwise.
759bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
760 APInt &KnownZero, APInt &KnownOne,
761 unsigned Depth) {
762 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
763 KnownZero, KnownOne, Depth);
764 if (NewVal == 0) return false;
765 U.set(NewVal);
766 return true;
767}
768
769
770/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
771/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000772/// that only the bits set in DemandedMask of the result of V are ever used
773/// downstream. Consequently, depending on the mask and V, it may be possible
774/// to replace V with a constant or one of its operands. In such cases, this
775/// function does the replacement and returns true. In all other cases, it
776/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000777/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000778/// to be zero in the expression. These are provided to potentially allow the
779/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
780/// the expression. KnownOne and KnownZero always follow the invariant that
781/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
782/// the bits in KnownOne and KnownZero may only be accurate for those bits set
783/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
784/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000785///
786/// This returns null if it did not change anything and it permits no
787/// simplification. This returns V itself if it did some simplification of V's
788/// operands based on the information about what bits are demanded. This returns
789/// some other non-null value if it found out that V is equal to another value
790/// in the context where the specified bits are demanded, but not for all users.
791Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
792 APInt &KnownZero, APInt &KnownOne,
793 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000794 assert(V != 0 && "Null pointer of Value???");
795 assert(Depth <= 6 && "Limit Search Depth");
796 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000797 const Type *VTy = V->getType();
798 assert((TD || !isa<PointerType>(VTy)) &&
799 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000800 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
801 (!VTy->isIntOrIntVector() ||
802 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000803 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000805 "Value *V, DemandedMask, KnownZero and KnownOne "
806 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000813 if (isa<ConstantPointerNull>(V)) {
814 // We know all of the bits for a constant!
815 KnownOne.clear();
816 KnownZero = DemandedMask;
817 return 0;
818 }
819
Chris Lattner08d2cc72009-01-31 07:26:06 +0000820 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000821 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000822 if (DemandedMask == 0) { // Not demanding any bits from V.
823 if (isa<UndefValue>(V))
824 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000825 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000826 }
827
Chris Lattner4598c942009-01-31 08:24:16 +0000828 if (Depth == 6) // Limit search depth.
829 return 0;
830
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000831 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
832 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
833
Dan Gohman1c8491e2009-04-25 17:12:48 +0000834 Instruction *I = dyn_cast<Instruction>(V);
835 if (!I) {
836 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
837 return 0; // Only analyze instructions.
838 }
839
Chris Lattner4598c942009-01-31 08:24:16 +0000840 // If there are multiple uses of this value and we aren't at the root, then
841 // we can't do any simplifications of the operands, because DemandedMask
842 // only reflects the bits demanded by *one* of the users.
843 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000844 // Despite the fact that we can't simplify this instruction in all User's
845 // context, we can at least compute the knownzero/knownone bits, and we can
846 // do simplifications that apply to *just* the one user if we know that
847 // this instruction has a simpler value in that context.
848 if (I->getOpcode() == Instruction::And) {
849 // If either the LHS or the RHS are Zero, the result is zero.
850 ComputeMaskedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1);
852 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853 LHSKnownZero, LHSKnownOne, Depth+1);
854
855 // If all of the demanded bits are known 1 on one side, return the other.
856 // These bits cannot contribute to the result of the 'and' in this
857 // context.
858 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
859 (DemandedMask & ~LHSKnownZero))
860 return I->getOperand(0);
861 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
862 (DemandedMask & ~RHSKnownZero))
863 return I->getOperand(1);
864
865 // If all of the demanded bits in the inputs are known zeros, return zero.
866 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000867 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000868
869 } else if (I->getOpcode() == Instruction::Or) {
870 // We can simplify (X|Y) -> X or Y in the user's context if we know that
871 // only bits from X or Y are demanded.
872
873 // If either the LHS or the RHS are One, the result is One.
874 ComputeMaskedBits(I->getOperand(1), DemandedMask,
875 RHSKnownZero, RHSKnownOne, Depth+1);
876 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
877 LHSKnownZero, LHSKnownOne, Depth+1);
878
879 // If all of the demanded bits are known zero on one side, return the
880 // other. These bits cannot contribute to the result of the 'or' in this
881 // context.
882 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
883 (DemandedMask & ~LHSKnownOne))
884 return I->getOperand(0);
885 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
886 (DemandedMask & ~RHSKnownOne))
887 return I->getOperand(1);
888
889 // If all of the potentially set bits on one side are known to be set on
890 // the other side, just use the 'other' side.
891 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
892 (DemandedMask & (~RHSKnownZero)))
893 return I->getOperand(0);
894 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
895 (DemandedMask & (~LHSKnownZero)))
896 return I->getOperand(1);
897 }
898
Chris Lattner4598c942009-01-31 08:24:16 +0000899 // Compute the KnownZero/KnownOne bits to simplify things downstream.
900 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
901 return 0;
902 }
903
904 // If this is the root being simplified, allow it to have multiple uses,
905 // just set the DemandedMask to all bits so that we can try to simplify the
906 // operands. This allows visitTruncInst (for example) to simplify the
907 // operand of a trunc without duplicating all the logic below.
908 if (Depth == 0 && !V->hasOneUse())
909 DemandedMask = APInt::getAllOnesValue(BitWidth);
910
Reid Spencer8cb68342007-03-12 17:25:59 +0000911 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000912 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000913 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000914 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000915 case Instruction::And:
916 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000917 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1) ||
919 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000920 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 return I;
922 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
923 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000924
925 // If all of the demanded bits are known 1 on one side, return the other.
926 // These bits cannot contribute to the result of the 'and'.
927 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
928 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000930 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
931 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000933
934 // If all of the demanded bits in the inputs are known zeros, return zero.
935 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000936 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000937
938 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000939 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000941
942 // Output known-1 bits are only known if set in both the LHS & RHS.
943 RHSKnownOne &= LHSKnownOne;
944 // Output known-0 are known to be clear if zero in either the LHS | RHS.
945 RHSKnownZero |= LHSKnownZero;
946 break;
947 case Instruction::Or:
948 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
950 RHSKnownZero, RHSKnownOne, Depth+1) ||
951 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000952 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000953 return I;
954 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
955 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the demanded bits are known zero on one side, return the other.
958 // These bits cannot contribute to the result of the 'or'.
959 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
960 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
963 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965
966 // If all of the potentially set bits on one side are known to be set on
967 // the other side, just use the 'other' side.
968 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
969 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000971 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
972 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000974
975 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000976 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000978
979 // Output known-0 bits are only known if clear in both the LHS & RHS.
980 RHSKnownZero &= LHSKnownZero;
981 // Output known-1 are known to be set if set in either the LHS | RHS.
982 RHSKnownOne |= LHSKnownOne;
983 break;
984 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1) ||
987 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I;
990 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
991 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // If all of the demanded bits are known zero on one side, return the other.
994 // These bits cannot contribute to the result of the 'xor'.
995 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000997 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000998 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000999
1000 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1002 (RHSKnownOne & LHSKnownOne);
1003 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1005 (RHSKnownOne & LHSKnownZero);
1006
1007 // If all of the demanded bits are known to be zero on one side or the
1008 // other, turn this into an *inclusive* or.
1009 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1011 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001012 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001013 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 }
1016
1017 // If all of the demanded bits on one side are known, and all of the set
1018 // bits on that side are also known to be set on the other side, turn this
1019 // into an AND, as we know the bits will be cleared.
1020 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1022 // all known
1023 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001024 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001026 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 }
1029 }
1030
1031 // If the RHS is a constant, see if we can simplify it.
1032 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001033 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 RHSKnownZero = KnownZeroOut;
1037 RHSKnownOne = KnownOneOut;
1038 break;
1039 }
1040 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042 RHSKnownZero, RHSKnownOne, Depth+1) ||
1043 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I;
1046 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1047 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001048
1049 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001050 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1051 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001053
1054 // Only known if known in both the LHS and RHS.
1055 RHSKnownOne &= LHSKnownOne;
1056 RHSKnownZero &= LHSKnownZero;
1057 break;
1058 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001059 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001060 DemandedMask.zext(truncBf);
1061 RHSKnownZero.zext(truncBf);
1062 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001063 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001064 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 DemandedMask.trunc(BitWidth);
1067 RHSKnownZero.trunc(BitWidth);
1068 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 break;
1071 }
1072 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001073 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001075
1076 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077 if (const VectorType *SrcVTy =
1078 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080 // Don't touch a bitcast between vectors of different element counts.
1081 return false;
1082 } else
1083 // Don't touch a scalar-to-vector bitcast.
1084 return false;
1085 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086 // Don't touch a vector-to-scalar bitcast.
1087 return false;
1088
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001090 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 break;
1094 case Instruction::ZExt: {
1095 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001096 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001097
Zhou Shengd48653a2007-03-29 04:45:55 +00001098 DemandedMask.trunc(SrcBitWidth);
1099 RHSKnownZero.trunc(SrcBitWidth);
1100 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001102 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001103 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001104 DemandedMask.zext(BitWidth);
1105 RHSKnownZero.zext(BitWidth);
1106 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001109 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 break;
1111 }
1112 case Instruction::SExt: {
1113 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001114 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001115
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001118
Zhou Sheng01542f32007-03-29 02:26:30 +00001119 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 // If any of the sign extended bits are demanded, we know that the sign
1121 // bit is demanded.
1122 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001123 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
Zhou Shengd48653a2007-03-29 04:45:55 +00001125 InputDemandedBits.trunc(SrcBitWidth);
1126 RHSKnownZero.trunc(SrcBitWidth);
1127 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001129 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 InputDemandedBits.zext(BitWidth);
1132 RHSKnownZero.zext(BitWidth);
1133 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001135
1136 // If the sign bit of the input is known set or clear, then we know the
1137 // top bits of the result.
1138
1139 // If the input sign bit is known zero, or if the NewBits are not demanded
1140 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001141 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 }
1148 break;
1149 }
1150 case Instruction::Add: {
1151 // Figure out what the input bits are. If the top bits of the and result
1152 // are not demanded, then the add doesn't demand them from its input
1153 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001155
1156 // If there is a constant on the RHS, there are a variety of xformations
1157 // we can do.
1158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 // If null, this should be simplified elsewhere. Some of the xforms here
1160 // won't work if the RHS is zero.
1161 if (RHS->isZero())
1162 break;
1163
1164 // If the top bit of the output is demanded, demand everything from the
1165 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001166 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001167
1168 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
1173 // If the RHS of the add has bits set that can't affect the input, reduce
1174 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001175 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001177
1178 // Avoid excess work.
1179 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1180 break;
1181
1182 // Turn it into OR if input bits are zero.
1183 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1184 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001185 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001187 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 }
1189
1190 // We can say something about the output known-zero and known-one bits,
1191 // depending on potential carries from the input constant and the
1192 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1193 // bits set and the RHS constant is 0x01001, then we know we have a known
1194 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1195
1196 // To compute this, we first compute the potential carry bits. These are
1197 // the bits which may be modified. I'm not aware of a better way to do
1198 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001200 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001201
1202 // Now that we know which bits have carries, compute the known-1/0 sets.
1203
1204 // Bits are known one if they are known zero in one operand and one in the
1205 // other, and there is no input carry.
1206 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1207 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1208
1209 // Bits are known zero if they are known zero in both operands and there
1210 // is no input carry.
1211 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1212 } else {
1213 // If the high-bits of this ADD are not demanded, then it does not demand
1214 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001215 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 // Right fill the mask of bits for this ADD to demand the most
1217 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220 LHSKnownZero, LHSKnownOne, Depth+1) ||
1221 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 }
1225 }
1226 break;
1227 }
1228 case Instruction::Sub:
1229 // If the high-bits of this SUB are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Right fill the mask of bits for this SUB to demand the most
1233 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001234 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001236 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237 LHSKnownZero, LHSKnownOne, Depth+1) ||
1238 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001242 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243 // the known zeros and ones.
1244 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 break;
1246 case Instruction::Shl:
1247 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001248 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001249 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 return I;
1253 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 RHSKnownZero <<= ShiftAmt;
1255 RHSKnownOne <<= ShiftAmt;
1256 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001257 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001258 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 }
1260 break;
1261 case Instruction::LShr:
1262 // For a logical shift right
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001265
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 return I;
1271 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001274 if (ShiftAmt) {
1275 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001277 RHSKnownZero |= HighBits; // high bits known zero.
1278 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 }
1280 break;
1281 case Instruction::AShr:
1282 // If this is an arithmetic shift right and only the low-bit is set, we can
1283 // always convert this into a logical shr, even if the shift amount is
1284 // variable. The low bit of the shift cannot be an input sign bit unless
1285 // the shift amount is >= the size of the datatype, which is undefined.
1286 if (DemandedMask == 1) {
1287 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001288 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001289 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001292
1293 // If the sign bit is the only bit demanded by this ashr, then there is no
1294 // need to do it, the shift doesn't change the high bit.
1295 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001297
1298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001299 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001303 // If any of the "high bits" are demanded, we should set the sign bit as
1304 // demanded.
1305 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return I;
1310 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001312 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1315
1316 // Handle the sign bits.
1317 APInt SignBit(APInt::getSignBit(BitWidth));
1318 // Adjust to where it is now in the mask.
1319 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1320
1321 // If the input sign bit is known to be zero, or if none of the top bits
1322 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001323 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 (HighBits & ~DemandedMask) == HighBits) {
1325 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330 RHSKnownOne |= HighBits;
1331 }
1332 }
1333 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001334 case Instruction::SRem:
1335 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001336 APInt RA = Rem->getValue().abs();
1337 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001338 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001340
Nick Lewycky8e394322008-11-02 02:41:50 +00001341 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346
1347 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349
1350 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001351
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 }
1354 }
1355 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001356 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001357 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360 KnownZero2, KnownOne2, Depth+1) ||
1361 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001362 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001364
Chris Lattner455e9ab2009-01-21 18:09:24 +00001365 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001366 Leaders = std::max(Leaders,
1367 KnownZero2.countLeadingOnes());
1368 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001371 case Instruction::Call:
1372 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373 switch (II->getIntrinsicID()) {
1374 default: break;
1375 case Intrinsic::bswap: {
1376 // If the only bits demanded come from one byte of the bswap result,
1377 // just shift the input byte into position to eliminate the bswap.
1378 unsigned NLZ = DemandedMask.countLeadingZeros();
1379 unsigned NTZ = DemandedMask.countTrailingZeros();
1380
1381 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1382 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1383 // have 14 leading zeros, round to 8.
1384 NLZ &= ~7;
1385 NTZ &= ~7;
1386 // If we need exactly one byte, we can do this transformation.
1387 if (BitWidth-NLZ-NTZ == 8) {
1388 unsigned ResultBit = NTZ;
1389 unsigned InputBit = BitWidth-NTZ-8;
1390
1391 // Replace this with either a left or right shift to get the byte into
1392 // the right place.
1393 Instruction *NewVal;
1394 if (InputBit > ResultBit)
1395 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001396 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001397 else
1398 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001399 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001400 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001401 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001402 }
1403
1404 // TODO: Could compute known zero/one bits based on the input.
1405 break;
1406 }
1407 }
1408 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001410 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001411 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001412
1413 // If the client is only demanding bits that we know, return the known
1414 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001415 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001416 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001417 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001418 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001419 return C;
1420 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001421 return false;
1422}
1423
Chris Lattner867b99f2006-10-05 06:55:50 +00001424
Mon P Wangaeb06d22008-11-10 04:46:22 +00001425/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001426/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001427/// actually used by the caller. This method analyzes which elements of the
1428/// operand are undef and returns that information in UndefElts.
1429///
1430/// If the information about demanded elements can be used to simplify the
1431/// operation, the operation is simplified, then the resultant value is
1432/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001433Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1434 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001436 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001437 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001438 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001439
1440 if (isa<UndefValue>(V)) {
1441 // If the entire vector is undefined, just return this info.
1442 UndefElts = EltMask;
1443 return 0;
1444 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001446 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001447 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001448
Chris Lattner867b99f2006-10-05 06:55:50 +00001449 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001450 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001452 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001453
1454 std::vector<Constant*> Elts;
1455 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001456 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001458 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1460 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001461 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 } else { // Otherwise, defined.
1463 Elts.push_back(CP->getOperand(i));
1464 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001465
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001467 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001468 return NewCP != CP ? NewCP : 0;
1469 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001470 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001472
1473 // Check if this is identity. If so, return 0 since we are not simplifying
1474 // anything.
1475 if (DemandedElts == ((1ULL << VWidth) -1))
1476 return 0;
1477
Reid Spencer9d6565a2007-02-15 02:26:10 +00001478 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001479 Constant *Zero = Context->getNullValue(EltTy);
1480 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001482 for (unsigned i = 0; i != VWidth; ++i) {
1483 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484 Elts.push_back(Elt);
1485 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001487 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 }
1489
Dan Gohman488fbfc2008-09-09 18:11:14 +00001490 // Limit search depth.
1491 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001492 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493
1494 // If multiple users are using the root value, procede with
1495 // simplification conservatively assuming that all elements
1496 // are needed.
1497 if (!V->hasOneUse()) {
1498 // Quit if we find multiple users of a non-root value though.
1499 // They'll be handled when it's their turn to be visited by
1500 // the main instcombine process.
1501 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001503 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001504
1505 // Conservatively assume that all elements are needed.
1506 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 }
1508
1509 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001510 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001511
1512 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001513 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 Value *TmpV;
1515 switch (I->getOpcode()) {
1516 default: break;
1517
1518 case Instruction::InsertElement: {
1519 // If this is a variable index, we don't know which element it overwrites.
1520 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001521 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 if (Idx == 0) {
1523 // Note that we can't propagate undef elt info, because we don't know
1524 // which elt is getting updated.
1525 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526 UndefElts2, Depth+1);
1527 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528 break;
1529 }
1530
1531 // If this is inserting an element that isn't demanded, remove this
1532 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001533 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001534 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001535 return AddSoonDeadInstToWorklist(*I, 0);
1536
1537 // Otherwise, the element inserted overwrites whatever was there, so the
1538 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001539 APInt DemandedElts2 = DemandedElts;
1540 DemandedElts2.clear(IdxNo);
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001542 UndefElts, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544
1545 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001546 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001547 break;
1548 }
1549 case Instruction::ShuffleVector: {
1550 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001551 uint64_t LHSVWidth =
1552 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001553 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001555 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001556 unsigned MaskVal = Shuffle->getMaskValue(i);
1557 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001559 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001560 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001561 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 else
Evan Cheng388df622009-02-03 10:05:09 +00001563 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 }
1565 }
1566 }
1567
Nate Begeman7b254672009-02-11 22:36:25 +00001568 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001570 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1572
Nate Begeman7b254672009-02-11 22:36:25 +00001573 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1575 UndefElts3, Depth+1);
1576 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1577
1578 bool NewUndefElts = false;
1579 for (unsigned i = 0; i < VWidth; i++) {
1580 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001581 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001582 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001583 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001584 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001585 NewUndefElts = true;
1586 UndefElts.set(i);
1587 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001589 if (UndefElts3[MaskVal - LHSVWidth]) {
1590 NewUndefElts = true;
1591 UndefElts.set(i);
1592 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 }
1594 }
1595
1596 if (NewUndefElts) {
1597 // Add additional discovered undefs.
1598 std::vector<Constant*> Elts;
1599 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001600 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001601 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001602 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001603 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 Shuffle->getMaskValue(i)));
1605 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001606 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001607 MadeChange = true;
1608 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 break;
1610 }
Chris Lattner69878332007-04-14 22:29:23 +00001611 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001612 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001613 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1614 if (!VTy) break;
1615 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001616 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001617 unsigned Ratio;
1618
1619 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001620 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001621 // elements as are demanded of us.
1622 Ratio = 1;
1623 InputDemandedElts = DemandedElts;
1624 } else if (VWidth > InVWidth) {
1625 // Untested so far.
1626 break;
1627
1628 // If there are more elements in the result than there are in the source,
1629 // then an input element is live if any of the corresponding output
1630 // elements are live.
1631 Ratio = VWidth/InVWidth;
1632 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001633 if (DemandedElts[OutIdx])
1634 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001635 }
1636 } else {
1637 // Untested so far.
1638 break;
1639
1640 // If there are more elements in the source than there are in the result,
1641 // then an input element is live if the corresponding output element is
1642 // live.
1643 Ratio = InVWidth/VWidth;
1644 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001645 if (DemandedElts[InIdx/Ratio])
1646 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001647 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001648
Chris Lattner69878332007-04-14 22:29:23 +00001649 // div/rem demand all inputs, because they don't want divide by zero.
1650 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1651 UndefElts2, Depth+1);
1652 if (TmpV) {
1653 I->setOperand(0, TmpV);
1654 MadeChange = true;
1655 }
1656
1657 UndefElts = UndefElts2;
1658 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001659 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001660 // If there are more elements in the result than there are in the source,
1661 // then an output element is undef if the corresponding input element is
1662 // undef.
1663 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001664 if (UndefElts2[OutIdx/Ratio])
1665 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001666 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001667 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001668 // If there are more elements in the source than there are in the result,
1669 // then a result element is undef if all of the corresponding input
1670 // elements are undef.
1671 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1672 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001673 if (!UndefElts2[InIdx]) // Not undef?
1674 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001675 }
1676 break;
1677 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001678 case Instruction::And:
1679 case Instruction::Or:
1680 case Instruction::Xor:
1681 case Instruction::Add:
1682 case Instruction::Sub:
1683 case Instruction::Mul:
1684 // div/rem demand all inputs, because they don't want divide by zero.
1685 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1686 UndefElts, Depth+1);
1687 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1688 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1689 UndefElts2, Depth+1);
1690 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1691
1692 // Output elements are undefined if both are undefined. Consider things
1693 // like undef&0. The result is known zero, not undef.
1694 UndefElts &= UndefElts2;
1695 break;
1696
1697 case Instruction::Call: {
1698 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1699 if (!II) break;
1700 switch (II->getIntrinsicID()) {
1701 default: break;
1702
1703 // Binary vector operations that work column-wise. A dest element is a
1704 // function of the corresponding input elements from the two inputs.
1705 case Intrinsic::x86_sse_sub_ss:
1706 case Intrinsic::x86_sse_mul_ss:
1707 case Intrinsic::x86_sse_min_ss:
1708 case Intrinsic::x86_sse_max_ss:
1709 case Intrinsic::x86_sse2_sub_sd:
1710 case Intrinsic::x86_sse2_mul_sd:
1711 case Intrinsic::x86_sse2_min_sd:
1712 case Intrinsic::x86_sse2_max_sd:
1713 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1714 UndefElts, Depth+1);
1715 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1716 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1717 UndefElts2, Depth+1);
1718 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1719
1720 // If only the low elt is demanded and this is a scalarizable intrinsic,
1721 // scalarize it now.
1722 if (DemandedElts == 1) {
1723 switch (II->getIntrinsicID()) {
1724 default: break;
1725 case Intrinsic::x86_sse_sub_ss:
1726 case Intrinsic::x86_sse_mul_ss:
1727 case Intrinsic::x86_sse2_sub_sd:
1728 case Intrinsic::x86_sse2_mul_sd:
1729 // TODO: Lower MIN/MAX/ABS/etc
1730 Value *LHS = II->getOperand(1);
1731 Value *RHS = II->getOperand(2);
1732 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001733 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1734 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1735 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1736 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001737
1738 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001739 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001740 case Intrinsic::x86_sse_sub_ss:
1741 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001742 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001743 II->getName()), *II);
1744 break;
1745 case Intrinsic::x86_sse_mul_ss:
1746 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001747 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001748 II->getName()), *II);
1749 break;
1750 }
1751
1752 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001753 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001754 Context->getUndef(II->getType()), TmpV,
1755 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 InsertNewInstBefore(New, *II);
1757 AddSoonDeadInstToWorklist(*II, 0);
1758 return New;
1759 }
1760 }
1761
1762 // Output elements are undefined if both are undefined. Consider things
1763 // like undef&0. The result is known zero, not undef.
1764 UndefElts &= UndefElts2;
1765 break;
1766 }
1767 break;
1768 }
1769 }
1770 return MadeChange ? I : 0;
1771}
1772
Dan Gohman45b4e482008-05-19 22:14:15 +00001773
Chris Lattner564a7272003-08-13 19:01:45 +00001774/// AssociativeOpt - Perform an optimization on an associative operator. This
1775/// function is designed to check a chain of associative operators for a
1776/// potential to apply a certain optimization. Since the optimization may be
1777/// applicable if the expression was reassociated, this checks the chain, then
1778/// reassociates the expression as necessary to expose the optimization
1779/// opportunity. This makes use of a special Functor, which must define
1780/// 'shouldApply' and 'apply' methods.
1781///
1782template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001783static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001784 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001785 unsigned Opcode = Root.getOpcode();
1786 Value *LHS = Root.getOperand(0);
1787
1788 // Quick check, see if the immediate LHS matches...
1789 if (F.shouldApply(LHS))
1790 return F.apply(Root);
1791
1792 // Otherwise, if the LHS is not of the same opcode as the root, return.
1793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001794 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 // Should we apply this transform to the RHS?
1796 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1797
1798 // If not to the RHS, check to see if we should apply to the LHS...
1799 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1801 ShouldApply = true;
1802 }
1803
1804 // If the functor wants to apply the optimization to the RHS of LHSI,
1805 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1806 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001807 // Now all of the instructions are in the current basic block, go ahead
1808 // and perform the reassociation.
1809 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1810
1811 // First move the selected RHS to the LHS of the root...
1812 Root.setOperand(0, LHSI->getOperand(1));
1813
1814 // Make what used to be the LHS of the root be the user of the root...
1815 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001816 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001817 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001818 return 0;
1819 }
Chris Lattner65725312004-04-16 18:08:07 +00001820 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001821 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001822 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001823 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001824 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001825
1826 // Now propagate the ExtraOperand down the chain of instructions until we
1827 // get to LHSI.
1828 while (TmpLHSI != LHSI) {
1829 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001830 // Move the instruction to immediately before the chain we are
1831 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001832 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001833 ARI = NextLHSI;
1834
Chris Lattner564a7272003-08-13 19:01:45 +00001835 Value *NextOp = NextLHSI->getOperand(1);
1836 NextLHSI->setOperand(1, ExtraOperand);
1837 TmpLHSI = NextLHSI;
1838 ExtraOperand = NextOp;
1839 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001840
Chris Lattner564a7272003-08-13 19:01:45 +00001841 // Now that the instructions are reassociated, have the functor perform
1842 // the transformation...
1843 return F.apply(Root);
1844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1847 }
1848 return 0;
1849}
1850
Dan Gohman844731a2008-05-13 00:00:25 +00001851namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001852
Nick Lewycky02d639f2008-05-23 04:34:58 +00001853// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001854struct AddRHS {
1855 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001856 LLVMContext *Context;
1857 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001858 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1859 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001860 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001861 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001862 }
1863};
1864
1865// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1866// iff C1&C2 == 0
1867struct AddMaskingAnd {
1868 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001869 LLVMContext *Context;
1870 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001871 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001872 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001873 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001874 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001875 }
1876 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001877 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879};
1880
Dan Gohman844731a2008-05-13 00:00:25 +00001881}
1882
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001884 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001885 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001886
Reid Spencer3da59db2006-11-27 01:05:10 +00001887 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001888 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001889 }
1890
Chris Lattner2eefe512004-04-09 19:05:30 +00001891 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1893 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001894
Chris Lattner2eefe512004-04-09 19:05:30 +00001895 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1896 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001897 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1898 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 }
1900
1901 Value *Op0 = SO, *Op1 = ConstOperand;
1902 if (!ConstIsRHS)
1903 std::swap(Op0, Op1);
1904 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001906 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001907 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001908 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1909 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001910 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001911 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001912 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001913 return IC->InsertNewInstBefore(New, I);
1914}
1915
1916// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917// constant as the other operand, try to fold the binary operator into the
1918// select arguments. This also works for Cast instructions, which obviously do
1919// not have a second operand.
1920static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1921 InstCombiner *IC) {
1922 // Don't modify shared select instructions
1923 if (!SI->hasOneUse()) return 0;
1924 Value *TV = SI->getOperand(1);
1925 Value *FV = SI->getOperand(2);
1926
1927 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001928 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001929 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001930
Chris Lattner6e7ba452005-01-01 16:22:27 +00001931 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1933
Gabor Greif051a9502008-04-06 20:25:17 +00001934 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1935 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936 }
1937 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001938}
1939
Chris Lattner4e998b22004-09-29 05:07:12 +00001940
1941/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942/// node as operand #0, see if we can fold the instruction into the PHI (which
1943/// is only possible if all operands to the PHI are constants).
1944Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001946 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001947 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001948
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001949 // Check to see if all of the operands of the PHI are constants. If there is
1950 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001951 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001952 BasicBlock *NonConstBB = 0;
1953 for (unsigned i = 0; i != NumPHIValues; ++i)
1954 if (!isa<Constant>(PN->getIncomingValue(i))) {
1955 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001956 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001957 NonConstBB = PN->getIncomingBlock(i);
1958
1959 // If the incoming non-constant value is in I's block, we have an infinite
1960 // loop.
1961 if (NonConstBB == I.getParent())
1962 return 0;
1963 }
1964
1965 // If there is exactly one non-constant value, we can insert a copy of the
1966 // operation in that block. However, if this is a critical edge, we would be
1967 // inserting the computation one some other paths (e.g. inside a loop). Only
1968 // do this if the pred block is unconditionally branching into the phi block.
1969 if (NonConstBB) {
1970 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971 if (!BI || !BI->isUnconditional()) return 0;
1972 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001973
1974 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001975 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001976 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001977 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001978 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001979
1980 // Next, add all of the operands to the PHI.
1981 if (I.getNumOperands() == 2) {
1982 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001983 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001984 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001985 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001987 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001988 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001989 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001990 } else {
1991 assert(PN->getIncomingBlock(i) == NonConstBB);
1992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001993 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001994 PN->getIncomingValue(i), C, "phitmp",
1995 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001996 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001997 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 CI->getPredicate(),
1999 PN->getIncomingValue(i), C, "phitmp",
2000 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002002 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002003
Chris Lattnerdbab3862007-03-02 21:28:56 +00002004 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 }
2006 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002007 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002008 } else {
2009 CastInst *CI = cast<CastInst>(&I);
2010 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002011 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002012 Value *InV;
2013 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002014 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 } else {
2016 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002017 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002018 I.getType(), "phitmp",
2019 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002020 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 }
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 }
2024 }
2025 return ReplaceInstUsesWith(I, NewPN);
2026}
2027
Chris Lattner2454a2e2008-01-29 06:52:45 +00002028
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002029/// WillNotOverflowSignedAdd - Return true if we can prove that:
2030/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2031/// This basically requires proving that the add in the original type would not
2032/// overflow to change the sign bit or have a carry out.
2033bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034 // There are different heuristics we can use for this. Here are some simple
2035 // ones.
2036
2037 // Add has the property that adding any two 2's complement numbers can only
2038 // have one carry bit which can change a sign. As such, if LHS and RHS each
2039 // have at least two sign bits, we know that the addition of the two values will
2040 // sign extend fine.
2041 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2042 return true;
2043
2044
2045 // If one of the operands only has one non-zero bit, and if the other operand
2046 // has a known-zero bit in a more significant place than it (not including the
2047 // sign bit) the ripple may go up to and fill the zero, but won't change the
2048 // sign. For example, (X & ~4) + 1.
2049
2050 // TODO: Implement.
2051
2052 return false;
2053}
2054
Chris Lattner2454a2e2008-01-29 06:52:45 +00002055
Chris Lattner7e708292002-06-25 16:13:24 +00002056Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002057 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002058 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002059
Chris Lattner66331a42004-04-10 22:01:55 +00002060 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002061 // X + undef -> undef
2062 if (isa<UndefValue>(RHS))
2063 return ReplaceInstUsesWith(I, RHS);
2064
Chris Lattner66331a42004-04-10 22:01:55 +00002065 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002066 if (RHSC->isNullValue())
2067 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002068
Chris Lattner66331a42004-04-10 22:01:55 +00002069 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002070 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002071 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002072 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002073 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002074 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002075
2076 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2077 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002078 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002079 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002080
Eli Friedman709b33d2009-07-13 22:27:52 +00002081 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002082 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002083 if (ZI->getSrcTy() == Type::Int1Ty)
2084 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002085 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002086
2087 if (isa<PHINode>(LHS))
2088 if (Instruction *NV = FoldOpIntoPhi(I))
2089 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002090
Chris Lattner4f637d42006-01-06 17:59:59 +00002091 ConstantInt *XorRHS = 0;
2092 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002093 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002094 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002095 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002096 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002097
Zhou Sheng4351c642007-04-02 08:20:41 +00002098 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002099 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002101 do {
2102 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002103 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002105 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002107 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002108 if (!MaskedValueIsZero(XorLHS,
2109 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002110 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002111 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002112 }
2113 }
2114 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 C0080Val = APIntOps::lshr(C0080Val, Size);
2116 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002118
Reid Spencer35c38852007-03-28 01:36:16 +00002119 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002120 // with funny bit widths then this switch statement should be removed. It
2121 // is just here to get the size of the "middle" type back up to something
2122 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002123 const Type *MiddleType = 0;
2124 switch (Size) {
2125 default: break;
2126 case 32: MiddleType = Type::Int32Ty; break;
2127 case 16: MiddleType = Type::Int16Ty; break;
2128 case 8: MiddleType = Type::Int8Ty; break;
2129 }
2130 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002131 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002132 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002133 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002134 }
2135 }
Chris Lattner66331a42004-04-10 22:01:55 +00002136 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002137
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002138 if (I.getType() == Type::Int1Ty)
2139 return BinaryOperator::CreateXor(LHS, RHS);
2140
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002141 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002142 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002143 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2144 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002145
2146 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2147 if (RHSI->getOpcode() == Instruction::Sub)
2148 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2149 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2150 }
2151 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2152 if (LHSI->getOpcode() == Instruction::Sub)
2153 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2154 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2155 }
Robert Bocchino71698282004-07-27 21:02:21 +00002156 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002157
Chris Lattner5c4afb92002-05-08 22:46:53 +00002158 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002159 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002160 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002161 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002162 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002164 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002165 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002166 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002167 }
2168
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002169 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002170 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002171
2172 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002173 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002174 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002176
Misha Brukmanfd939082005-04-21 23:48:37 +00002177
Chris Lattner50af16a2004-11-13 19:50:12 +00002178 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002179 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002180 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002181 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002182
2183 // X*C1 + X*C2 --> X * (C1+C2)
2184 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002185 if (X == dyn_castFoldableMul(RHS, C1, Context))
2186 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002187 }
2188
2189 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002190 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2191 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002192
Chris Lattnere617c9e2007-01-05 02:17:46 +00002193 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002194 if (dyn_castNotVal(LHS, Context) == RHS ||
2195 dyn_castNotVal(RHS, Context) == LHS)
2196 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002197
Chris Lattnerad3448c2003-02-18 19:57:07 +00002198
Chris Lattner564a7272003-08-13 19:01:45 +00002199 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002200 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002201 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002202 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002203
2204 // A+B --> A|B iff A and B have no bits set in common.
2205 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2206 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2207 APInt LHSKnownOne(IT->getBitWidth(), 0);
2208 APInt LHSKnownZero(IT->getBitWidth(), 0);
2209 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2210 if (LHSKnownZero != 0) {
2211 APInt RHSKnownOne(IT->getBitWidth(), 0);
2212 APInt RHSKnownZero(IT->getBitWidth(), 0);
2213 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2214
2215 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002216 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002217 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002218 }
2219 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002220
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002221 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002222 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002223 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002224 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2225 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002226 if (W != Y) {
2227 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002228 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002229 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002230 std::swap(W, X);
2231 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002232 std::swap(Y, Z);
2233 std::swap(W, X);
2234 }
2235 }
2236
2237 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002238 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002239 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002240 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002241 }
2242 }
2243 }
2244
Chris Lattner6b032052003-10-02 15:11:26 +00002245 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002246 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002247 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002248 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002249
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002250 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002251 if (LHS->hasOneUse() &&
2252 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002253 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 if (Anded == CRHS) {
2255 // See if all bits from the first bit set in the Add RHS up are included
2256 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002257 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258
2259 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002260 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002261
2262 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002263 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002264
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002265 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2266 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002267 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002268 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002269 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270 }
2271 }
2272 }
2273
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002274 // Try to fold constant add into select arguments.
2275 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002276 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002277 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002278 }
2279
Chris Lattner42790482007-12-20 01:56:58 +00002280 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002281 {
2282 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002283 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002284 if (!SI) {
2285 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002286 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002287 }
Chris Lattner42790482007-12-20 01:56:58 +00002288 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002289 Value *TV = SI->getTrueValue();
2290 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002292
2293 // Can we fold the add into the argument of the select?
2294 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002295 if (match(FV, m_Zero(), *Context) &&
2296 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002297 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002298 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002299 if (match(TV, m_Zero(), *Context) &&
2300 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002301 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002302 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002303 }
2304 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002305
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002306 // Check for (add (sext x), y), see if we can merge this into an
2307 // integer add followed by a sext.
2308 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2309 // (add (sext x), cst) --> (sext (add x, cst'))
2310 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2311 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002312 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002313 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002314 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002315 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2316 // Insert the new, smaller add.
2317 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2318 CI, "addconv");
2319 InsertNewInstBefore(NewAdd, I);
2320 return new SExtInst(NewAdd, I.getType());
2321 }
2322 }
2323
2324 // (add (sext x), (sext y)) --> (sext (add int x, y))
2325 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2326 // Only do this if x/y have the same type, if at last one of them has a
2327 // single use (so we don't increase the number of sexts), and if the
2328 // integer add will not overflow.
2329 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2330 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2331 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2332 RHSConv->getOperand(0))) {
2333 // Insert the new integer add.
2334 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2335 RHSConv->getOperand(0),
2336 "addconv");
2337 InsertNewInstBefore(NewAdd, I);
2338 return new SExtInst(NewAdd, I.getType());
2339 }
2340 }
2341 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002342
2343 return Changed ? &I : 0;
2344}
2345
2346Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2347 bool Changed = SimplifyCommutative(I);
2348 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2349
2350 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2351 // X + 0 --> X
2352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002353 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002354 (I.getType())->getValueAPF()))
2355 return ReplaceInstUsesWith(I, LHS);
2356 }
2357
2358 if (isa<PHINode>(LHS))
2359 if (Instruction *NV = FoldOpIntoPhi(I))
2360 return NV;
2361 }
2362
2363 // -A + B --> B - A
2364 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002365 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002366 return BinaryOperator::CreateFSub(RHS, LHSV);
2367
2368 // A + -B --> A - B
2369 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002370 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002371 return BinaryOperator::CreateFSub(LHS, V);
2372
2373 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2375 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2376 return ReplaceInstUsesWith(I, LHS);
2377
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002378 // Check for (add double (sitofp x), y), see if we can merge this into an
2379 // integer add followed by a promotion.
2380 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2381 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2382 // ... if the constant fits in the integer value. This is useful for things
2383 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2384 // requires a constant pool load, and generally allows the add to be better
2385 // instcombined.
2386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2387 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002388 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002389 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002390 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002391 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2392 // Insert the new integer add.
2393 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2394 CI, "addconv");
2395 InsertNewInstBefore(NewAdd, I);
2396 return new SIToFPInst(NewAdd, I.getType());
2397 }
2398 }
2399
2400 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2401 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2402 // Only do this if x/y have the same type, if at last one of them has a
2403 // single use (so we don't increase the number of int->fp conversions),
2404 // and if the integer add will not overflow.
2405 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2406 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2407 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2408 RHSConv->getOperand(0))) {
2409 // Insert the new integer add.
2410 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2411 RHSConv->getOperand(0),
2412 "addconv");
2413 InsertNewInstBefore(NewAdd, I);
2414 return new SIToFPInst(NewAdd, I.getType());
2415 }
2416 }
2417 }
2418
Chris Lattner7e708292002-06-25 16:13:24 +00002419 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002420}
2421
Chris Lattner7e708292002-06-25 16:13:24 +00002422Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002424
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002425 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002426 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002427
Chris Lattner233f7dc2002-08-12 21:17:25 +00002428 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002429 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002430 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002431
Chris Lattnere87597f2004-10-16 18:11:37 +00002432 if (isa<UndefValue>(Op0))
2433 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2434 if (isa<UndefValue>(Op1))
2435 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2436
Chris Lattnerd65460f2003-11-05 01:06:05 +00002437 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2438 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002439 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002440 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002441
Chris Lattnerd65460f2003-11-05 01:06:05 +00002442 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002443 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002444 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002445 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002446
Chris Lattner76b7a062007-01-15 07:02:54 +00002447 // -(X >>u 31) -> (X >>s 31)
2448 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002449 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002450 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002451 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002452 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002453 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002454 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002455 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002457 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002458 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002459 }
2460 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002461 }
2462 else if (SI->getOpcode() == Instruction::AShr) {
2463 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2464 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002465 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002466 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002467 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002468 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002469 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002470 }
2471 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002472 }
2473 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002474 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002475
2476 // Try to fold constant sub into select arguments.
2477 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002478 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002479 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002480
2481 // C - zext(bool) -> bool ? C - 1 : C
2482 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2483 if (ZI->getSrcTy() == Type::Int1Ty)
2484 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002485 }
2486
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002487 if (I.getType() == Type::Int1Ty)
2488 return BinaryOperator::CreateXor(Op0, Op1);
2489
Chris Lattner43d84d62005-04-07 16:15:25 +00002490 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002491 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002492 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002493 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2494 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002495 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002496 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2497 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002498 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2499 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2500 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002501 return BinaryOperator::CreateSub(
2502 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002503 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002504 }
2505
Chris Lattnerfd059242003-10-15 16:48:29 +00002506 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002507 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2508 // is not used by anyone else...
2509 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002510 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002511 // Swap the two operands of the subexpr...
2512 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2513 Op1I->setOperand(0, IIOp1);
2514 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002515
Chris Lattnera2881962003-02-18 19:28:33 +00002516 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002518 }
2519
2520 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2521 //
2522 if (Op1I->getOpcode() == Instruction::And &&
2523 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2524 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2525
Chris Lattnerf523d062004-06-09 05:08:07 +00002526 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002527 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2528 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002529 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002530 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002531
Reid Spencerac5209e2006-10-16 23:08:08 +00002532 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002533 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002534 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002535 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002536 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002537 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002538 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002539
Chris Lattnerad3448c2003-02-18 19:57:07 +00002540 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002541 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002542 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2543 Constant *CP1 =
2544 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002545 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002546 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002547 }
Chris Lattner40371712002-05-09 01:29:19 +00002548 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002549 }
Chris Lattnera2881962003-02-18 19:28:33 +00002550
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002551 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2552 if (Op0I->getOpcode() == Instruction::Add) {
2553 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2554 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2555 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2556 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2557 } else if (Op0I->getOpcode() == Instruction::Sub) {
2558 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002559 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2560 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002561 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002562 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002563
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002565 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002566 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002567 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002568
Chris Lattner50af16a2004-11-13 19:50:12 +00002569 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002570 if (X == dyn_castFoldableMul(Op1, C2, Context))
2571 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002572 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002573 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002574}
2575
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002580 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 return BinaryOperator::CreateFAdd(Op0, V);
2582
2583 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2584 if (Op1I->getOpcode() == Instruction::FAdd) {
2585 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002586 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2587 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002588 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002589 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2590 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 }
2593
2594 return 0;
2595}
2596
Chris Lattnera0141b92007-07-15 20:42:37 +00002597/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2598/// comparison only checks the sign bit. If it only checks the sign bit, set
2599/// TrueIfSigned if the result of the comparison is true when the input value is
2600/// signed.
2601static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2602 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002603 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002604 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2605 TrueIfSigned = true;
2606 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002607 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2608 TrueIfSigned = true;
2609 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002610 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2611 TrueIfSigned = false;
2612 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002613 case ICmpInst::ICMP_UGT:
2614 // True if LHS u> RHS and RHS == high-bit-mask - 1
2615 TrueIfSigned = true;
2616 return RHS->getValue() ==
2617 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2618 case ICmpInst::ICMP_UGE:
2619 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2620 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002621 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002622 default:
2623 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002624 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002625}
2626
Chris Lattner7e708292002-06-25 16:13:24 +00002627Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002628 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002629 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002630
Eli Friedman1694e092009-07-18 09:12:15 +00002631 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002632 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002633
Chris Lattner233f7dc2002-08-12 21:17:25 +00002634 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002635 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2636 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002637
2638 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002639 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002640 if (SI->getOpcode() == Instruction::Shl)
2641 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002642 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002643 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002644
Zhou Sheng843f07672007-04-19 05:39:12 +00002645 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002646 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2647 if (CI->equalsInt(1)) // X * 1 == X
2648 return ReplaceInstUsesWith(I, Op0);
2649 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002650 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002651
Zhou Sheng97b52c22007-03-29 01:57:21 +00002652 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002653 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002654 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002655 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002656 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002657 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002658 if (Op1->isNullValue())
2659 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002660
2661 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2662 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002663 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002664
2665 // As above, vector X*splat(1.0) -> X in all defined cases.
2666 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002667 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2668 if (CI->equalsInt(1))
2669 return ReplaceInstUsesWith(I, Op0);
2670 }
2671 }
Chris Lattnera2881962003-02-18 19:28:33 +00002672 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002673
2674 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2675 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002676 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002677 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002679 Op1, "tmp");
2680 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002681 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002682 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002683 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002684
2685 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002686
2687 // Try to fold constant mul into select arguments.
2688 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002689 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002690 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002691
2692 if (isa<PHINode>(Op0))
2693 if (Instruction *NV = FoldOpIntoPhi(I))
2694 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002695 }
2696
Owen Andersond672ecb2009-07-03 00:17:18 +00002697 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2698 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002699 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002700
Nick Lewycky0c730792008-11-21 07:33:58 +00002701 // (X / Y) * Y = X - (X % Y)
2702 // (X / Y) * -Y = (X % Y) - X
2703 {
2704 Value *Op1 = I.getOperand(1);
2705 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2706 if (!BO ||
2707 (BO->getOpcode() != Instruction::UDiv &&
2708 BO->getOpcode() != Instruction::SDiv)) {
2709 Op1 = Op0;
2710 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2711 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002712 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002713 if (BO && BO->hasOneUse() &&
2714 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2715 (BO->getOpcode() == Instruction::UDiv ||
2716 BO->getOpcode() == Instruction::SDiv)) {
2717 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2718
2719 Instruction *Rem;
2720 if (BO->getOpcode() == Instruction::UDiv)
2721 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2722 else
2723 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2724
2725 InsertNewInstBefore(Rem, I);
2726 Rem->takeName(BO);
2727
2728 if (Op1BO == Op1)
2729 return BinaryOperator::CreateSub(Op0BO, Rem);
2730 else
2731 return BinaryOperator::CreateSub(Rem, Op0BO);
2732 }
2733 }
2734
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002735 if (I.getType() == Type::Int1Ty)
2736 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2737
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002738 // If one of the operands of the multiply is a cast from a boolean value, then
2739 // we know the bool is either zero or one, so this is a 'masking' multiply.
2740 // See if we can simplify things based on how the boolean was originally
2741 // formed.
2742 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002743 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002744 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002745 BoolCast = CI;
2746 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002747 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002748 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749 BoolCast = CI;
2750 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002751 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2753 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002754 bool TIS = false;
2755
Reid Spencere4d87aa2006-12-23 06:05:41 +00002756 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002757 // multiply into a shift/and combination.
2758 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002759 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2760 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002761 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002762 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002763 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002764 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002765 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002766 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002767 BoolCast->getOperand(0)->getName()+
2768 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769
2770 // If the multiply type is not the same as the source type, sign extend
2771 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002772 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002773 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2774 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002775 Instruction::CastOps opcode =
2776 (SrcBits == DstBits ? Instruction::BitCast :
2777 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2778 V = InsertCastBefore(opcode, V, I.getType(), I);
2779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002780
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002782 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002783 }
2784 }
2785 }
2786
Chris Lattner7e708292002-06-25 16:13:24 +00002787 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002788}
2789
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002790Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2791 bool Changed = SimplifyCommutative(I);
2792 Value *Op0 = I.getOperand(0);
2793
2794 // Simplify mul instructions with a constant RHS...
2795 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2796 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2797 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2798 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2799 if (Op1F->isExactlyValue(1.0))
2800 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2801 } else if (isa<VectorType>(Op1->getType())) {
2802 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2803 // As above, vector X*splat(1.0) -> X in all defined cases.
2804 if (Constant *Splat = Op1V->getSplatValue()) {
2805 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2806 if (F->isExactlyValue(1.0))
2807 return ReplaceInstUsesWith(I, Op0);
2808 }
2809 }
2810 }
2811
2812 // Try to fold constant mul into select arguments.
2813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2815 return R;
2816
2817 if (isa<PHINode>(Op0))
2818 if (Instruction *NV = FoldOpIntoPhi(I))
2819 return NV;
2820 }
2821
Owen Andersond672ecb2009-07-03 00:17:18 +00002822 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2823 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002824 return BinaryOperator::CreateFMul(Op0v, Op1v);
2825
2826 return Changed ? &I : 0;
2827}
2828
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002829/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2830/// instruction.
2831bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2832 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2833
2834 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2835 int NonNullOperand = -1;
2836 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2837 if (ST->isNullValue())
2838 NonNullOperand = 2;
2839 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2840 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2841 if (ST->isNullValue())
2842 NonNullOperand = 1;
2843
2844 if (NonNullOperand == -1)
2845 return false;
2846
2847 Value *SelectCond = SI->getOperand(0);
2848
2849 // Change the div/rem to use 'Y' instead of the select.
2850 I.setOperand(1, SI->getOperand(NonNullOperand));
2851
2852 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2853 // problem. However, the select, or the condition of the select may have
2854 // multiple uses. Based on our knowledge that the operand must be non-zero,
2855 // propagate the known value for the select into other uses of it, and
2856 // propagate a known value of the condition into its other users.
2857
2858 // If the select and condition only have a single use, don't bother with this,
2859 // early exit.
2860 if (SI->use_empty() && SelectCond->hasOneUse())
2861 return true;
2862
2863 // Scan the current block backward, looking for other uses of SI.
2864 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2865
2866 while (BBI != BBFront) {
2867 --BBI;
2868 // If we found a call to a function, we can't assume it will return, so
2869 // information from below it cannot be propagated above it.
2870 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2871 break;
2872
2873 // Replace uses of the select or its condition with the known values.
2874 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2875 I != E; ++I) {
2876 if (*I == SI) {
2877 *I = SI->getOperand(NonNullOperand);
2878 AddToWorkList(BBI);
2879 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002880 *I = NonNullOperand == 1 ? Context->getTrue() :
2881 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002882 AddToWorkList(BBI);
2883 }
2884 }
2885
2886 // If we past the instruction, quit looking for it.
2887 if (&*BBI == SI)
2888 SI = 0;
2889 if (&*BBI == SelectCond)
2890 SelectCond = 0;
2891
2892 // If we ran out of things to eliminate, break out of the loop.
2893 if (SelectCond == 0 && SI == 0)
2894 break;
2895
2896 }
2897 return true;
2898}
2899
2900
Reid Spencer1628cec2006-10-26 06:15:43 +00002901/// This function implements the transforms on div instructions that work
2902/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2903/// used by the visitors to those instructions.
2904/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002905Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002907
Chris Lattner50b2ca42008-02-19 06:12:18 +00002908 // undef / X -> 0 for integer.
2909 // undef / X -> undef for FP (the undef could be a snan).
2910 if (isa<UndefValue>(Op0)) {
2911 if (Op0->getType()->isFPOrFPVector())
2912 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002913 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002914 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002915
2916 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002917 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002918 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002919
Reid Spencer1628cec2006-10-26 06:15:43 +00002920 return 0;
2921}
Misha Brukmanfd939082005-04-21 23:48:37 +00002922
Reid Spencer1628cec2006-10-26 06:15:43 +00002923/// This function implements the transforms common to both integer division
2924/// instructions (udiv and sdiv). It is called by the visitors to those integer
2925/// division instructions.
2926/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002927Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002930 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002931 if (Op0 == Op1) {
2932 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002933 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002934 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002935 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002936 }
2937
Owen Andersond672ecb2009-07-03 00:17:18 +00002938 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002939 return ReplaceInstUsesWith(I, CI);
2940 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002941
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 if (Instruction *Common = commonDivTransforms(I))
2943 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002944
2945 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2946 // This does not apply for fdiv.
2947 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2948 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002949
2950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2951 // div X, 1 == X
2952 if (RHS->equalsInt(1))
2953 return ReplaceInstUsesWith(I, Op0);
2954
2955 // (X / C1) / C2 -> X / (C1*C2)
2956 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2957 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2958 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002959 if (MultiplyOverflows(RHS, LHSRHS,
2960 I.getOpcode()==Instruction::SDiv, Context))
2961 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002962 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002963 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002964 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002965 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002966
Reid Spencerbca0e382007-03-23 20:05:17 +00002967 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002968 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2969 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2970 return R;
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2973 return NV;
2974 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002975 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002976
Chris Lattnera2881962003-02-18 19:28:33 +00002977 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002978 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002979 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00002980 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002981
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002982 // It can't be division by zero, hence it must be division by one.
2983 if (I.getType() == Type::Int1Ty)
2984 return ReplaceInstUsesWith(I, Op0);
2985
Nick Lewycky895f0852008-11-27 20:21:08 +00002986 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2987 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2988 // div X, 1 == X
2989 if (X->isOne())
2990 return ReplaceInstUsesWith(I, Op0);
2991 }
2992
Reid Spencer1628cec2006-10-26 06:15:43 +00002993 return 0;
2994}
2995
2996Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2998
2999 // Handle the integer div common cases
3000 if (Instruction *Common = commonIDivTransforms(I))
3001 return Common;
3002
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003004 // X udiv C^2 -> X >> C
3005 // Check to see if this is an unsigned division with an exact power of 2,
3006 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003007 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003008 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003009 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003010
3011 // X udiv C, where C >= signbit
3012 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003013 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3014 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003015 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003016 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3017 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003018 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003019 }
3020
3021 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003022 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 if (RHSI->getOpcode() == Instruction::Shl &&
3024 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003025 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003026 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003028 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003029 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003030 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003031 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003032 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003033 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003034 }
3035 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003036 }
3037
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3039 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003040 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003041 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003042 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003043 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003044 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003045 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003046 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003047 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003048 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003049 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 Op0, TC, SI->getName()+".t");
3051 TSI = InsertNewInstBefore(TSI, I);
3052
3053 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003054 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003055 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003056 Op0, FC, SI->getName()+".f");
3057 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003058
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003059 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003060 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003061 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003062 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003063 return 0;
3064}
3065
Reid Spencer1628cec2006-10-26 06:15:43 +00003066Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3067 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3068
3069 // Handle the integer div common cases
3070 if (Instruction *Common = commonIDivTransforms(I))
3071 return Common;
3072
3073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3074 // sdiv X, -1 == -X
3075 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003076 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003077 }
3078
3079 // If the sign bits of both operands are zero (i.e. we can prove they are
3080 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003081 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003082 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003083 if (MaskedValueIsZero(Op0, Mask)) {
3084 if (MaskedValueIsZero(Op1, Mask)) {
3085 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3087 }
3088 ConstantInt *ShiftedInt;
3089 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3090 ShiftedInt->getValue().isPowerOf2()) {
3091 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3092 // Safe because the only negative value (1 << Y) can take on is
3093 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3094 // the sign bit set.
3095 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3096 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003097 }
Eli Friedman8be17392009-07-18 09:53:21 +00003098 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003099
3100 return 0;
3101}
3102
3103Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3104 return commonDivTransforms(I);
3105}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003106
Reid Spencer0a783f72006-11-02 01:53:59 +00003107/// This function implements the transforms on rem instructions that work
3108/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3109/// is used by the visitors to those instructions.
3110/// @brief Transforms common to all three rem instructions
3111Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003113
Chris Lattner50b2ca42008-02-19 06:12:18 +00003114 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3115 if (I.getType()->isFPOrFPVector())
3116 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003117 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003118 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003119 if (isa<UndefValue>(Op1))
3120 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003121
3122 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003123 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3124 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003125
Reid Spencer0a783f72006-11-02 01:53:59 +00003126 return 0;
3127}
3128
3129/// This function implements the transforms common to both integer remainder
3130/// instructions (urem and srem). It is called by the visitors to those integer
3131/// remainder instructions.
3132/// @brief Common integer remainder transforms
3133Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3134 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3135
3136 if (Instruction *common = commonRemTransforms(I))
3137 return common;
3138
Dale Johannesened6af242009-01-21 00:35:19 +00003139 // 0 % X == 0 for integer, we don't need to preserve faults!
3140 if (Constant *LHS = dyn_cast<Constant>(Op0))
3141 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003142 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003143
Chris Lattner857e8cd2004-12-12 21:48:58 +00003144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003145 // X % 0 == undef, we don't need to preserve faults!
3146 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003147 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003148
Chris Lattnera2881962003-02-18 19:28:33 +00003149 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003150 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003151
Chris Lattner97943922006-02-28 05:49:21 +00003152 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3155 return R;
3156 } else if (isa<PHINode>(Op0I)) {
3157 if (Instruction *NV = FoldOpIntoPhi(I))
3158 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003159 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003160
3161 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003162 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003163 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003164 }
Chris Lattnera2881962003-02-18 19:28:33 +00003165 }
3166
Reid Spencer0a783f72006-11-02 01:53:59 +00003167 return 0;
3168}
3169
3170Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3172
3173 if (Instruction *common = commonIRemTransforms(I))
3174 return common;
3175
3176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3177 // X urem C^2 -> X and C
3178 // Check to see if this is an unsigned remainder with an exact power of 2,
3179 // if so, convert to a bitwise and.
3180 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003181 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003182 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003183 }
3184
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003185 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003186 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3187 if (RHSI->getOpcode() == Instruction::Shl &&
3188 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003189 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003190 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003191 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003192 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003193 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003194 }
3195 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003197
Reid Spencer0a783f72006-11-02 01:53:59 +00003198 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3199 // where C1&C2 are powers of two.
3200 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3201 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3202 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3203 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003204 if ((STO->getValue().isPowerOf2()) &&
3205 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003207 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3208 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003210 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3211 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003212 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003213 }
3214 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003215 }
3216
Chris Lattner3f5b8772002-05-06 16:14:14 +00003217 return 0;
3218}
3219
Reid Spencer0a783f72006-11-02 01:53:59 +00003220Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3222
Dan Gohmancff55092007-11-05 23:16:33 +00003223 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003224 if (Instruction *common = commonIRemTransforms(I))
3225 return common;
3226
Owen Andersond672ecb2009-07-03 00:17:18 +00003227 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003228 if (!isa<Constant>(RHSNeg) ||
3229 (isa<ConstantInt>(RHSNeg) &&
3230 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003231 // X % -Y -> X % Y
3232 AddUsesToWorkList(I);
3233 I.setOperand(1, RHSNeg);
3234 return &I;
3235 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003236
Dan Gohmancff55092007-11-05 23:16:33 +00003237 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003239 if (I.getType()->isInteger()) {
3240 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3241 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3242 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003243 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003244 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 }
3246
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003247 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003248 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3249 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003250
Nick Lewycky9dce8732008-12-20 16:48:00 +00003251 bool hasNegative = false;
3252 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3253 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3254 if (RHS->getValue().isNegative())
3255 hasNegative = true;
3256
3257 if (hasNegative) {
3258 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003259 for (unsigned i = 0; i != VWidth; ++i) {
3260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3261 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003262 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003263 else
3264 Elts[i] = RHS;
3265 }
3266 }
3267
Owen Andersond672ecb2009-07-03 00:17:18 +00003268 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003269 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003270 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003271 I.setOperand(1, NewRHSV);
3272 return &I;
3273 }
3274 }
3275 }
3276
Reid Spencer0a783f72006-11-02 01:53:59 +00003277 return 0;
3278}
3279
3280Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 return commonRemTransforms(I);
3282}
3283
Chris Lattner457dd822004-06-09 07:59:58 +00003284// isOneBitSet - Return true if there is exactly one bit set in the specified
3285// constant.
3286static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003287 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003288}
3289
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003290// isHighOnes - Return true if the constant is of the form 1+0+.
3291// This is the same as lowones(~X).
3292static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003293 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003294}
3295
Reid Spencere4d87aa2006-12-23 06:05:41 +00003296/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003297/// are carefully arranged to allow folding of expressions such as:
3298///
3299/// (A < B) | (A > B) --> (A != B)
3300///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003301/// Note that this is only valid if the first and second predicates have the
3302/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003303///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003304/// Three bits are used to represent the condition, as follows:
3305/// 0 A > B
3306/// 1 A == B
3307/// 2 A < B
3308///
3309/// <=> Value Definition
3310/// 000 0 Always false
3311/// 001 1 A > B
3312/// 010 2 A == B
3313/// 011 3 A >= B
3314/// 100 4 A < B
3315/// 101 5 A != B
3316/// 110 6 A <= B
3317/// 111 7 Always true
3318///
3319static unsigned getICmpCode(const ICmpInst *ICI) {
3320 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003321 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003322 case ICmpInst::ICMP_UGT: return 1; // 001
3323 case ICmpInst::ICMP_SGT: return 1; // 001
3324 case ICmpInst::ICMP_EQ: return 2; // 010
3325 case ICmpInst::ICMP_UGE: return 3; // 011
3326 case ICmpInst::ICMP_SGE: return 3; // 011
3327 case ICmpInst::ICMP_ULT: return 4; // 100
3328 case ICmpInst::ICMP_SLT: return 4; // 100
3329 case ICmpInst::ICMP_NE: return 5; // 101
3330 case ICmpInst::ICMP_ULE: return 6; // 110
3331 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003332 // True -> 7
3333 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003334 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003335 return 0;
3336 }
3337}
3338
Evan Cheng8db90722008-10-14 17:15:11 +00003339/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3340/// predicate into a three bit mask. It also returns whether it is an ordered
3341/// predicate by reference.
3342static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3343 isOrdered = false;
3344 switch (CC) {
3345 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3346 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003347 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3348 case FCmpInst::FCMP_UGT: return 1; // 001
3349 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3350 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003351 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3352 case FCmpInst::FCMP_UGE: return 3; // 011
3353 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3354 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003355 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3356 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003357 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3358 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003359 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003360 default:
3361 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003362 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003363 return 0;
3364 }
3365}
3366
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367/// getICmpValue - This is the complement of getICmpCode, which turns an
3368/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003369/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003370/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003371static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003372 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003374 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003375 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 case 1:
3377 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003378 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 else
Owen Anderson333c4002009-07-09 23:48:35 +00003380 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3381 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003382 case 3:
3383 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003384 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 else
Owen Anderson333c4002009-07-09 23:48:35 +00003386 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 case 4:
3388 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003389 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 else
Owen Anderson333c4002009-07-09 23:48:35 +00003391 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3392 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 case 6:
3394 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003395 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 else
Owen Anderson333c4002009-07-09 23:48:35 +00003397 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003398 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003399 }
3400}
3401
Evan Cheng8db90722008-10-14 17:15:11 +00003402/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3403/// opcode and two operands into either a FCmp instruction. isordered is passed
3404/// in to determine which kind of predicate to use in the new fcmp instruction.
3405static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003406 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003407 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003408 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003409 case 0:
3410 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003411 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003412 else
Owen Anderson333c4002009-07-09 23:48:35 +00003413 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003414 case 1:
3415 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003416 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003417 else
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003419 case 2:
3420 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003421 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003422 else
Owen Anderson333c4002009-07-09 23:48:35 +00003423 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003424 case 3:
3425 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003426 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003427 else
Owen Anderson333c4002009-07-09 23:48:35 +00003428 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003429 case 4:
3430 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003431 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003432 else
Owen Anderson333c4002009-07-09 23:48:35 +00003433 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003434 case 5:
3435 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003436 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003437 else
Owen Anderson333c4002009-07-09 23:48:35 +00003438 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003439 case 6:
3440 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003441 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 else
Owen Anderson333c4002009-07-09 23:48:35 +00003443 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003444 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003445 }
3446}
3447
Chris Lattnerb9553d62008-11-16 04:55:20 +00003448/// PredicatesFoldable - Return true if both predicates match sign or if at
3449/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003450static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3451 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003452 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3453 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454}
3455
3456namespace {
3457// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3458struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003459 InstCombiner &IC;
3460 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461 ICmpInst::Predicate pred;
3462 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3463 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3464 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003465 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3467 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003468 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3469 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 return false;
3471 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 Instruction *apply(Instruction &Log) const {
3473 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3474 if (ICI->getOperand(0) != LHS) {
3475 assert(ICI->getOperand(1) == LHS);
3476 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003477 }
3478
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003479 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003481 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482 unsigned Code;
3483 switch (Log.getOpcode()) {
3484 case Instruction::And: Code = LHSCode & RHSCode; break;
3485 case Instruction::Or: Code = LHSCode | RHSCode; break;
3486 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003487 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 }
3489
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003490 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3491 ICmpInst::isSignedPredicate(ICI->getPredicate());
3492
Owen Andersond672ecb2009-07-03 00:17:18 +00003493 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 if (Instruction *I = dyn_cast<Instruction>(RV))
3495 return I;
3496 // Otherwise, it's a constant boolean value...
3497 return IC.ReplaceInstUsesWith(Log, RV);
3498 }
3499};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003500} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3503// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003504// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003506 ConstantInt *OpRHS,
3507 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508 BinaryOperator &TheAnd) {
3509 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003510 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003511 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003512 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003513
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003514 switch (Op->getOpcode()) {
3515 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003516 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003517 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003518 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003520 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 }
3523 break;
3524 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003525 if (Together == AndRHS) // (X | C) & C --> C
3526 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003527
Chris Lattner6e7ba452005-01-01 16:22:27 +00003528 if (Op->hasOneUse() && Together != OpRHS) {
3529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003531 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003532 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534 }
3535 break;
3536 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003537 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 // Adding a one to a single bit bit-field should be turned into an XOR
3539 // of the bit. First thing to check is to see if this AND is with a
3540 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003541 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542
3543 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003544 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545 // Ok, at this point, we know that we are masking the result of the
3546 // ADD down to exactly one bit. If the constant we are adding has
3547 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003548 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003549
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 // Check to see if any bits below the one bit set in AndRHSV are set.
3551 if ((AddRHS & (AndRHSV-1)) == 0) {
3552 // If not, the only thing that can effect the output of the AND is
3553 // the bit specified by AndRHSV. If that bit is set, the effect of
3554 // the XOR is to toggle the bit. If it is clear, then the ADD has
3555 // no effect.
3556 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3557 TheAnd.setOperand(0, X);
3558 return &TheAnd;
3559 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003560 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003561 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003562 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003563 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 }
3566 }
3567 }
3568 }
3569 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003570
3571 case Instruction::Shl: {
3572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now!
3574 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003575 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003576 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003577 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003578 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003579
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 if (CI->getValue() == ShlMask) {
3581 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003582 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3583 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003584 TheAnd.setOperand(1, CI);
3585 return &TheAnd;
3586 }
3587 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003588 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003589 case Instruction::LShr:
3590 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003591 // We know that the AND will not produce any of the bits shifted in, so if
3592 // the anded constant includes them, clear them now! This only applies to
3593 // unsigned shifts, because a signed shr may bring in set bits!
3594 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003598 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003599
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 if (CI->getValue() == ShrMask) {
3601 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003602 return ReplaceInstUsesWith(TheAnd, Op);
3603 } else if (CI != AndRHS) {
3604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3605 return &TheAnd;
3606 }
3607 break;
3608 }
3609 case Instruction::AShr:
3610 // Signed shr.
3611 // See if this is shifting in some sign extension, then masking it out
3612 // with an and.
3613 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003614 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003615 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003616 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003617 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003618 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003619 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003620 // Make the argument unsigned.
3621 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003622 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003623 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003624 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003625 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003626 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003627 }
3628 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003629 }
3630 return 0;
3631}
3632
Chris Lattner8b170942002-08-09 23:47:40 +00003633
Chris Lattnera96879a2004-09-29 17:40:11 +00003634/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3635/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3637/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003638/// insert new instructions.
3639Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640 bool isSigned, bool Inside,
3641 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003642 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003643 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003644 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 if (Inside) {
3647 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003648 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003649
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003651 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003652 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003654 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655 }
3656
3657 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003658 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003659 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003660 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003661 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003662 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003663 }
3664
3665 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003666 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003667
Reid Spencere4e40032007-03-21 23:19:50 +00003668 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003669 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 ICmpInst::Predicate pred = (isSigned ?
3672 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003673 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003675
Reid Spencere4e40032007-03-21 23:19:50 +00003676 // Emit V-Lo >u Hi-1-Lo
3677 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003678 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003679 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003680 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003681 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003682 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003683}
3684
Chris Lattner7203e152005-09-18 07:22:02 +00003685// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3687// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3688// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003689static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003690 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003691 uint32_t BitWidth = Val->getType()->getBitWidth();
3692 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003693
3694 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003695 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003696 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003697 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003698 return true;
3699}
3700
Chris Lattner7203e152005-09-18 07:22:02 +00003701/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702/// where isSub determines whether the operator is a sub. If we can fold one of
3703/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003704///
3705/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708///
3709/// return (A +/- B).
3710///
3711Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003712 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003713 Instruction &I) {
3714 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715 if (!LHSI || LHSI->getNumOperands() != 2 ||
3716 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3717
3718 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3719
3720 switch (LHSI->getOpcode()) {
3721 default: return 0;
3722 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003723 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003724 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003725 if ((Mask->getValue().countLeadingZeros() +
3726 Mask->getValue().countPopulation()) ==
3727 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003728 break;
3729
3730 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731 // part, we don't need any explicit masks to take them out of A. If that
3732 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003733 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003734 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003735 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003736 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003737 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003738 break;
3739 }
3740 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003741 return 0;
3742 case Instruction::Or:
3743 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003744 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003745 if ((Mask->getValue().countLeadingZeros() +
3746 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003747 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003748 break;
3749 return 0;
3750 }
3751
3752 Instruction *New;
3753 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003754 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003755 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003756 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003757 return InsertNewInstBefore(New, I);
3758}
3759
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003760/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3761Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3762 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003763 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003764 ConstantInt *LHSCst, *RHSCst;
3765 ICmpInst::Predicate LHSCC, RHSCC;
3766
Chris Lattnerea065fb2008-11-16 05:10:52 +00003767 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003768 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3769 m_ConstantInt(LHSCst)), *Context) ||
3770 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3771 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003772 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003773
3774 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3775 // where C is a power of 2
3776 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3777 LHSCst->getValue().isPowerOf2()) {
3778 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3779 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003780 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003781 }
3782
3783 // From here on, we only handle:
3784 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3785 if (Val != Val2) return 0;
3786
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003787 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3788 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3789 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3790 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3791 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3792 return 0;
3793
3794 // We can't fold (ugt x, C) & (sgt x, C2).
3795 if (!PredicatesFoldable(LHSCC, RHSCC))
3796 return 0;
3797
3798 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003799 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 if (ICmpInst::isSignedPredicate(LHSCC) ||
3801 (ICmpInst::isEquality(LHSCC) &&
3802 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003803 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003805 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3806
3807 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003808 std::swap(LHS, RHS);
3809 std::swap(LHSCst, RHSCst);
3810 std::swap(LHSCC, RHSCC);
3811 }
3812
3813 // At this point, we know we have have two icmp instructions
3814 // comparing a value against two constants and and'ing the result
3815 // together. Because of the above check, we know that we only have
3816 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3817 // (from the FoldICmpLogical check above), that the two constants
3818 // are not equal and that the larger constant is on the RHS
3819 assert(LHSCst != RHSCst && "Compares not folded above?");
3820
3821 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003822 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 case ICmpInst::ICMP_EQ:
3824 switch (RHSCC) {
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: // (X == 13 & X == 15) -> false
3827 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3828 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003829 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003830 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3831 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3832 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3833 return ReplaceInstUsesWith(I, LHS);
3834 }
3835 case ICmpInst::ICMP_NE:
3836 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003837 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003838 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003839 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003840 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 break; // (X != 13 & X u< 15) -> no change
3842 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003843 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003844 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003845 break; // (X != 13 & X s< 15) -> no change
3846 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3847 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3848 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3849 return ReplaceInstUsesWith(I, RHS);
3850 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003851 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3852 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003853 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3854 Val->getName()+".off");
3855 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003856 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003857 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 }
3859 break; // (X != 13 & X != 15) -> no change
3860 }
3861 break;
3862 case ICmpInst::ICMP_ULT:
3863 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003864 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003865 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003867 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003868 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3869 break;
3870 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3871 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3874 break;
3875 }
3876 break;
3877 case ICmpInst::ICMP_SLT:
3878 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003879 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3881 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003882 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3884 break;
3885 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3886 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3887 return ReplaceInstUsesWith(I, LHS);
3888 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3889 break;
3890 }
3891 break;
3892 case ICmpInst::ICMP_UGT:
3893 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003894 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003895 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3896 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3897 return ReplaceInstUsesWith(I, RHS);
3898 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3899 break;
3900 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003901 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003902 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003903 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003904 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003905 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3906 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3908 break;
3909 }
3910 break;
3911 case ICmpInst::ICMP_SGT:
3912 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3915 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3916 return ReplaceInstUsesWith(I, RHS);
3917 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003920 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003921 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003923 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003924 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3925 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3927 break;
3928 }
3929 break;
3930 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931
3932 return 0;
3933}
3934
3935
Chris Lattner7e708292002-06-25 16:13:24 +00003936Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003937 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003939
Chris Lattnere87597f2004-10-16 18:11:37 +00003940 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003941 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003942
Chris Lattner6e7ba452005-01-01 16:22:27 +00003943 // and X, X = X
3944 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003945 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003946
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003947 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003948 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003949 if (SimplifyDemandedInstructionBits(I))
3950 return &I;
3951 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003952 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003953 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003954 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003955 } else if (isa<ConstantAggregateZero>(Op1)) {
3956 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003957 }
3958 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003959
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003960 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003961 const APInt& AndRHSMask = AndRHS->getValue();
3962 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003963
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003964 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003965 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003966 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003967 Value *Op0LHS = Op0I->getOperand(0);
3968 Value *Op0RHS = Op0I->getOperand(1);
3969 switch (Op0I->getOpcode()) {
3970 case Instruction::Xor:
3971 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003972 // If the mask is only needed on one incoming arm, push it up.
3973 if (Op0I->hasOneUse()) {
3974 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3975 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003976 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003977 Op0RHS->getName()+".masked");
3978 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003979 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003980 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003981 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003982 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003983 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3984 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003985 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003986 Op0LHS->getName()+".masked");
3987 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003988 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003989 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3990 }
3991 }
3992
Chris Lattner6e7ba452005-01-01 16:22:27 +00003993 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003994 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003995 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3996 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3998 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003999 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004000 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004001 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004002 break;
4003
4004 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004005 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4006 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4008 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004009 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004010
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004011 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4012 // has 1's for all bits that the subtraction with A might affect.
4013 if (Op0I->hasOneUse()) {
4014 uint32_t BitWidth = AndRHSMask.getBitWidth();
4015 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4016 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4017
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004018 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004019 if (!(A && A->isZero()) && // avoid infinite recursion.
4020 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004021 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004022 InsertNewInstBefore(NewNeg, I);
4023 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4024 }
4025 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004027
4028 case Instruction::Shl:
4029 case Instruction::LShr:
4030 // (1 << x) & 1 --> zext(x == 0)
4031 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004032 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004033 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4034 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004035 InsertNewInstBefore(NewICmp, I);
4036 return new ZExtInst(NewICmp, I.getType());
4037 }
4038 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004039 }
4040
Chris Lattner58403262003-07-23 19:25:52 +00004041 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004042 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004043 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004044 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004045 // If this is an integer truncation or change from signed-to-unsigned, and
4046 // if the source is an and/or with immediate, transform it. This
4047 // frequently occurs for bitfield accesses.
4048 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004049 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004050 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004051 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004052 if (CastOp->getOpcode() == Instruction::And) {
4053 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004054 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4055 // This will fold the two constants together, which may allow
4056 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004057 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004058 CastOp->getOperand(0), I.getType(),
4059 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004060 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004061 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004062 Constant *C3 =
4063 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4064 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004065 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004066 } else if (CastOp->getOpcode() == Instruction::Or) {
4067 // Change: and (cast (or X, C1) to T), C2
4068 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004069 Constant *C3 =
4070 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4071 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4072 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004073 return ReplaceInstUsesWith(I, AndRHS);
4074 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004075 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004076 }
Chris Lattner06782f82003-07-23 19:36:21 +00004077 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004078
4079 // Try to fold constant and into select arguments.
4080 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004081 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004082 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004083 if (isa<PHINode>(Op0))
4084 if (Instruction *NV = FoldOpIntoPhi(I))
4085 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004086 }
4087
Owen Andersond672ecb2009-07-03 00:17:18 +00004088 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4089 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004090
Chris Lattner5b62aa72004-06-18 06:07:51 +00004091 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004092 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004093
Misha Brukmancb6267b2004-07-30 12:50:08 +00004094 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004095 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004096 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004097 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004098 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004099 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004100 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004101
4102 {
Chris Lattner003b6202007-06-15 05:58:24 +00004103 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004104 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004105 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4106 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004107
4108 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004109 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004110 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004111 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004112 }
4113 }
4114
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004115 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004116 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4117 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004118
4119 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004120 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004121 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004122 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004123 }
4124 }
Chris Lattner64daab52006-04-01 08:03:55 +00004125
4126 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004127 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004128 if (A == Op1) { // (A^B)&A -> A&(A^B)
4129 I.swapOperands(); // Simplify below
4130 std::swap(Op0, Op1);
4131 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4132 cast<BinaryOperator>(Op0)->swapOperands();
4133 I.swapOperands(); // Simplify below
4134 std::swap(Op0, Op1);
4135 }
4136 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004137
Chris Lattner64daab52006-04-01 08:03:55 +00004138 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004139 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004140 if (B == Op0) { // B&(A^B) -> B&(B^A)
4141 cast<BinaryOperator>(Op1)->swapOperands();
4142 std::swap(A, B);
4143 }
4144 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004145 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004146 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004147 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004148 }
4149 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004150
4151 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004152 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4153 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004154 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004155 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4156 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004157 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004158 }
4159
Reid Spencere4d87aa2006-12-23 06:05:41 +00004160 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4161 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004162 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004163 return R;
4164
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004165 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4166 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4167 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004168 }
4169
Chris Lattner6fc205f2006-05-05 06:39:07 +00004170 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004171 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4172 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4173 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4174 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004175 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004176 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004177 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4178 I.getType(), TD) &&
4179 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4180 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004182 Op1C->getOperand(0),
4183 I.getName());
4184 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004185 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004186 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004187 }
Chris Lattnere511b742006-11-14 07:46:50 +00004188
4189 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004190 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4191 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4192 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004193 SI0->getOperand(1) == SI1->getOperand(1) &&
4194 (SI0->hasOneUse() || SI1->hasOneUse())) {
4195 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004196 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004197 SI1->getOperand(0),
4198 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004199 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004200 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004201 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004202 }
4203
Evan Cheng8db90722008-10-14 17:15:11 +00004204 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004205 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4206 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4207 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004208 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4209 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004210 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4211 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4212 // If either of the constants are nans, then the whole thing returns
4213 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004214 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004215 return ReplaceInstUsesWith(I, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004216 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4217 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004218 }
Evan Cheng8db90722008-10-14 17:15:11 +00004219 } else {
4220 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4221 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004222 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4223 m_Value(Op0RHS)), *Context) &&
4224 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4225 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004226 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4227 // Swap RHS operands to match LHS.
4228 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4229 std::swap(Op1LHS, Op1RHS);
4230 }
Evan Cheng8db90722008-10-14 17:15:11 +00004231 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4232 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4233 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004234 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4235 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004236 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4237 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004238 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004239 else if (Op0CC == FCmpInst::FCMP_TRUE)
4240 return ReplaceInstUsesWith(I, Op1);
4241 else if (Op1CC == FCmpInst::FCMP_TRUE)
4242 return ReplaceInstUsesWith(I, Op0);
4243 bool Op0Ordered;
4244 bool Op1Ordered;
4245 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4246 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4247 if (Op1Pred == 0) {
4248 std::swap(Op0, Op1);
4249 std::swap(Op0Pred, Op1Pred);
4250 std::swap(Op0Ordered, Op1Ordered);
4251 }
4252 if (Op0Pred == 0) {
4253 // uno && ueq -> uno && (uno || eq) -> ueq
4254 // ord && olt -> ord && (ord && lt) -> olt
4255 if (Op0Ordered == Op1Ordered)
4256 return ReplaceInstUsesWith(I, Op1);
4257 // uno && oeq -> uno && (ord && eq) -> false
4258 // uno && ord -> false
4259 if (!Op0Ordered)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004260 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004261 // ord && ueq -> ord && (uno || eq) -> oeq
4262 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004263 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004264 }
4265 }
4266 }
4267 }
Chris Lattner99c65742007-10-24 05:38:08 +00004268 }
4269 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004270
Chris Lattner7e708292002-06-25 16:13:24 +00004271 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004272}
4273
Chris Lattner8c34cd22008-10-05 02:13:19 +00004274/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4275/// capable of providing pieces of a bswap. The subexpression provides pieces
4276/// of a bswap if it is proven that each of the non-zero bytes in the output of
4277/// the expression came from the corresponding "byte swapped" byte in some other
4278/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4279/// we know that the expression deposits the low byte of %X into the high byte
4280/// of the bswap result and that all other bytes are zero. This expression is
4281/// accepted, the high byte of ByteValues is set to X to indicate a correct
4282/// match.
4283///
4284/// This function returns true if the match was unsuccessful and false if so.
4285/// On entry to the function the "OverallLeftShift" is a signed integer value
4286/// indicating the number of bytes that the subexpression is later shifted. For
4287/// example, if the expression is later right shifted by 16 bits, the
4288/// OverallLeftShift value would be -2 on entry. This is used to specify which
4289/// byte of ByteValues is actually being set.
4290///
4291/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4292/// byte is masked to zero by a user. For example, in (X & 255), X will be
4293/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4294/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4295/// always in the local (OverallLeftShift) coordinate space.
4296///
4297static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4298 SmallVector<Value*, 8> &ByteValues) {
4299 if (Instruction *I = dyn_cast<Instruction>(V)) {
4300 // If this is an or instruction, it may be an inner node of the bswap.
4301 if (I->getOpcode() == Instruction::Or) {
4302 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4303 ByteValues) ||
4304 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4305 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004306 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004307
4308 // If this is a logical shift by a constant multiple of 8, recurse with
4309 // OverallLeftShift and ByteMask adjusted.
4310 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4311 unsigned ShAmt =
4312 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4313 // Ensure the shift amount is defined and of a byte value.
4314 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4315 return true;
4316
4317 unsigned ByteShift = ShAmt >> 3;
4318 if (I->getOpcode() == Instruction::Shl) {
4319 // X << 2 -> collect(X, +2)
4320 OverallLeftShift += ByteShift;
4321 ByteMask >>= ByteShift;
4322 } else {
4323 // X >>u 2 -> collect(X, -2)
4324 OverallLeftShift -= ByteShift;
4325 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004326 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004327 }
4328
4329 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4330 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4331
4332 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4333 ByteValues);
4334 }
4335
4336 // If this is a logical 'and' with a mask that clears bytes, clear the
4337 // corresponding bytes in ByteMask.
4338 if (I->getOpcode() == Instruction::And &&
4339 isa<ConstantInt>(I->getOperand(1))) {
4340 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4341 unsigned NumBytes = ByteValues.size();
4342 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4343 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4344
4345 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4346 // If this byte is masked out by a later operation, we don't care what
4347 // the and mask is.
4348 if ((ByteMask & (1 << i)) == 0)
4349 continue;
4350
4351 // If the AndMask is all zeros for this byte, clear the bit.
4352 APInt MaskB = AndMask & Byte;
4353 if (MaskB == 0) {
4354 ByteMask &= ~(1U << i);
4355 continue;
4356 }
4357
4358 // If the AndMask is not all ones for this byte, it's not a bytezap.
4359 if (MaskB != Byte)
4360 return true;
4361
4362 // Otherwise, this byte is kept.
4363 }
4364
4365 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4366 ByteValues);
4367 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004368 }
4369
Chris Lattner8c34cd22008-10-05 02:13:19 +00004370 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4371 // the input value to the bswap. Some observations: 1) if more than one byte
4372 // is demanded from this input, then it could not be successfully assembled
4373 // into a byteswap. At least one of the two bytes would not be aligned with
4374 // their ultimate destination.
4375 if (!isPowerOf2_32(ByteMask)) return true;
4376 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004377
Chris Lattner8c34cd22008-10-05 02:13:19 +00004378 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4379 // is demanded, it needs to go into byte 0 of the result. This means that the
4380 // byte needs to be shifted until it lands in the right byte bucket. The
4381 // shift amount depends on the position: if the byte is coming from the high
4382 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4383 // low part, it must be shifted left.
4384 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4385 if (InputByteNo < ByteValues.size()/2) {
4386 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4387 return true;
4388 } else {
4389 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4390 return true;
4391 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392
4393 // If the destination byte value is already defined, the values are or'd
4394 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004395 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004396 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004397 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004398 return false;
4399}
4400
4401/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4402/// If so, insert the new bswap intrinsic and return it.
4403Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004404 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 if (!ITy || ITy->getBitWidth() % 16 ||
4406 // ByteMask only allows up to 32-byte values.
4407 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004408 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409
4410 /// ByteValues - For each byte of the result, we keep track of which value
4411 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004412 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004413 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004414
4415 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004416 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4417 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004418 return 0;
4419
4420 // Check to see if all of the bytes come from the same value.
4421 Value *V = ByteValues[0];
4422 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4423
4424 // Check to make sure that all of the bytes come from the same value.
4425 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4426 if (ByteValues[i] != V)
4427 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004428 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004430 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004431 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004432}
4433
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004434/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4435/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4436/// we can simplify this expression to "cond ? C : D or B".
4437static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004438 Value *C, Value *D,
4439 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004440 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004441 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004442 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004443 return 0;
4444
Chris Lattnera6a474d2008-11-16 04:26:55 +00004445 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004446 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004447 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004448 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004449 return SelectInst::Create(Cond, C, B);
4450 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004451 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004452 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004453 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004454 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004455 return 0;
4456}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004457
Chris Lattner69d4ced2008-11-16 05:20:07 +00004458/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4459Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4460 ICmpInst *LHS, ICmpInst *RHS) {
4461 Value *Val, *Val2;
4462 ConstantInt *LHSCst, *RHSCst;
4463 ICmpInst::Predicate LHSCC, RHSCC;
4464
4465 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004466 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4467 m_ConstantInt(LHSCst)), *Context) ||
4468 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4469 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004470 return 0;
4471
4472 // From here on, we only handle:
4473 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4474 if (Val != Val2) return 0;
4475
4476 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4477 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4478 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4479 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4480 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4481 return 0;
4482
4483 // We can't fold (ugt x, C) | (sgt x, C2).
4484 if (!PredicatesFoldable(LHSCC, RHSCC))
4485 return 0;
4486
4487 // Ensure that the larger constant is on the RHS.
4488 bool ShouldSwap;
4489 if (ICmpInst::isSignedPredicate(LHSCC) ||
4490 (ICmpInst::isEquality(LHSCC) &&
4491 ICmpInst::isSignedPredicate(RHSCC)))
4492 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4493 else
4494 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4495
4496 if (ShouldSwap) {
4497 std::swap(LHS, RHS);
4498 std::swap(LHSCst, RHSCst);
4499 std::swap(LHSCC, RHSCC);
4500 }
4501
4502 // At this point, we know we have have two icmp instructions
4503 // comparing a value against two constants and or'ing the result
4504 // together. Because of the above check, we know that we only have
4505 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4506 // FoldICmpLogical check above), that the two constants are not
4507 // equal.
4508 assert(LHSCst != RHSCst && "Compares not folded above?");
4509
4510 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004511 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004512 case ICmpInst::ICMP_EQ:
4513 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004514 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004515 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004516 if (LHSCst == SubOne(RHSCst, Context)) {
4517 // (X == 13 | X == 14) -> X-13 <u 2
4518 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004519 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4520 Val->getName()+".off");
4521 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004522 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004523 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004524 }
4525 break; // (X == 13 | X == 15) -> no change
4526 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4527 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4528 break;
4529 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4530 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4531 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4532 return ReplaceInstUsesWith(I, RHS);
4533 }
4534 break;
4535 case ICmpInst::ICMP_NE:
4536 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004537 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004538 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4539 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4540 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4541 return ReplaceInstUsesWith(I, LHS);
4542 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4543 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4544 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004545 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004546 }
4547 break;
4548 case ICmpInst::ICMP_ULT:
4549 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004550 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004551 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4552 break;
4553 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4554 // If RHSCst is [us]MAXINT, it is always false. Not handling
4555 // this can cause overflow.
4556 if (RHSCst->isMaxValue(false))
4557 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004558 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4559 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004560 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4561 break;
4562 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4563 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4564 return ReplaceInstUsesWith(I, RHS);
4565 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4566 break;
4567 }
4568 break;
4569 case ICmpInst::ICMP_SLT:
4570 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004571 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004572 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4573 break;
4574 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4575 // If RHSCst is [us]MAXINT, it is always false. Not handling
4576 // this can cause overflow.
4577 if (RHSCst->isMaxValue(true))
4578 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004579 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4580 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004581 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4582 break;
4583 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4584 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4585 return ReplaceInstUsesWith(I, RHS);
4586 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4587 break;
4588 }
4589 break;
4590 case ICmpInst::ICMP_UGT:
4591 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004592 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4594 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4595 return ReplaceInstUsesWith(I, LHS);
4596 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4597 break;
4598 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4599 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004600 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004601 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4602 break;
4603 }
4604 break;
4605 case ICmpInst::ICMP_SGT:
4606 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004607 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004608 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4609 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4610 return ReplaceInstUsesWith(I, LHS);
4611 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4612 break;
4613 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4614 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004615 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004616 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4617 break;
4618 }
4619 break;
4620 }
4621 return 0;
4622}
4623
Bill Wendlinga698a472008-12-01 08:23:25 +00004624/// FoldOrWithConstants - This helper function folds:
4625///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004626/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004627///
4628/// into:
4629///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004630/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004631///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004632/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004633Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004634 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004635 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4636 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004637
Bill Wendling286a0542008-12-02 06:24:20 +00004638 Value *V1 = 0;
4639 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004640 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004641
Bill Wendling29976b92008-12-02 06:18:11 +00004642 APInt Xor = CI1->getValue() ^ CI2->getValue();
4643 if (!Xor.isAllOnesValue()) return 0;
4644
Bill Wendling286a0542008-12-02 06:24:20 +00004645 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004646 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004647 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4648 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004649 }
4650
4651 return 0;
4652}
4653
Chris Lattner7e708292002-06-25 16:13:24 +00004654Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004655 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004656 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004657
Chris Lattner42593e62007-03-24 23:56:43 +00004658 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004659 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004660
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004661 // or X, X = X
4662 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004663 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004664
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004665 // See if we can simplify any instructions used by the instruction whose sole
4666 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004667 if (SimplifyDemandedInstructionBits(I))
4668 return &I;
4669 if (isa<VectorType>(I.getType())) {
4670 if (isa<ConstantAggregateZero>(Op1)) {
4671 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4672 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4673 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4674 return ReplaceInstUsesWith(I, I.getOperand(1));
4675 }
Chris Lattner42593e62007-03-24 23:56:43 +00004676 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004677
Chris Lattner3f5b8772002-05-06 16:14:14 +00004678 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004679 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004680 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004681 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004682 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4683 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004684 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004685 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004686 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004687 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004688 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004689 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004690
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004691 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004692 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4693 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004694 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004695 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004696 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004697 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004698 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004699 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004700
4701 // Try to fold constant and into select arguments.
4702 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004703 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004704 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004705 if (isa<PHINode>(Op0))
4706 if (Instruction *NV = FoldOpIntoPhi(I))
4707 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004708 }
4709
Chris Lattner4f637d42006-01-06 17:59:59 +00004710 Value *A = 0, *B = 0;
4711 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004712
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004713 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004714 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4715 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004716 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004717 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4718 return ReplaceInstUsesWith(I, Op0);
4719
Chris Lattner6423d4c2006-07-10 20:25:24 +00004720 // (A | B) | C and A | (B | C) -> bswap if possible.
4721 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004722 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4723 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4724 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4725 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004726 if (Instruction *BSwap = MatchBSwap(I))
4727 return BSwap;
4728 }
4729
Chris Lattner6e4c6492005-05-09 04:58:36 +00004730 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004731 if (Op0->hasOneUse() &&
4732 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004733 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004734 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004735 InsertNewInstBefore(NOr, I);
4736 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004737 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004738 }
4739
4740 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004741 if (Op1->hasOneUse() &&
4742 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004743 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004744 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004745 InsertNewInstBefore(NOr, I);
4746 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004748 }
4749
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004750 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004751 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004752 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4753 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004754 Value *V1 = 0, *V2 = 0, *V3 = 0;
4755 C1 = dyn_cast<ConstantInt>(C);
4756 C2 = dyn_cast<ConstantInt>(D);
4757 if (C1 && C2) { // (A & C1)|(B & C2)
4758 // If we have: ((V + N) & C1) | (V & C2)
4759 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4760 // replace with V+N.
4761 if (C1->getValue() == ~C2->getValue()) {
4762 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004763 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004764 // Add commutes, try both ways.
4765 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4766 return ReplaceInstUsesWith(I, A);
4767 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4768 return ReplaceInstUsesWith(I, A);
4769 }
4770 // Or commutes, try both ways.
4771 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004772 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004773 // Add commutes, try both ways.
4774 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4775 return ReplaceInstUsesWith(I, B);
4776 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4777 return ReplaceInstUsesWith(I, B);
4778 }
4779 }
Chris Lattner044e5332007-04-08 08:01:49 +00004780 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004781 }
4782
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004783 // Check to see if we have any common things being and'ed. If so, find the
4784 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004785 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4786 if (A == B) // (A & C)|(A & D) == A & (C|D)
4787 V1 = A, V2 = C, V3 = D;
4788 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4789 V1 = A, V2 = B, V3 = C;
4790 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4791 V1 = C, V2 = A, V3 = D;
4792 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4793 V1 = C, V2 = A, V3 = B;
4794
4795 if (V1) {
4796 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004797 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4798 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004799 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004800 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004801
Dan Gohman1975d032008-10-30 20:40:10 +00004802 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004803 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004804 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004805 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004806 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004807 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004808 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004809 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004810 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004811
Bill Wendlingb01865c2008-11-30 13:52:49 +00004812 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004813 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4814 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004815 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004816 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004817 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4818 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004819 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004820 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004821 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4822 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004823 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004824 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004825 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4826 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004827 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004828 }
Chris Lattnere511b742006-11-14 07:46:50 +00004829
4830 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004831 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4832 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4833 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004834 SI0->getOperand(1) == SI1->getOperand(1) &&
4835 (SI0->hasOneUse() || SI1->hasOneUse())) {
4836 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004837 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004838 SI1->getOperand(0),
4839 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004840 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004841 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004842 }
4843 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004844
Bill Wendlingb3833d12008-12-01 01:07:11 +00004845 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004846 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4847 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004848 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004849 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004850 }
4851 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004852 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4853 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004854 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004855 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004856 }
4857
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004858 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004859 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004860 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004861 } else {
4862 A = 0;
4863 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004864 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004865 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004866 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004867 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004868
Misha Brukmancb6267b2004-07-30 12:50:08 +00004869 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004870 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004871 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004872 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004873 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004874 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004875 }
Chris Lattnera2881962003-02-18 19:28:33 +00004876
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4878 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004879 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004880 return R;
4881
Chris Lattner69d4ced2008-11-16 05:20:07 +00004882 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4883 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4884 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004885 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004886
4887 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004888 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004889 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004890 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004891 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4892 !isa<ICmpInst>(Op1C->getOperand(0))) {
4893 const Type *SrcTy = Op0C->getOperand(0)->getType();
4894 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4895 // Only do this if the casts both really cause code to be
4896 // generated.
4897 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4898 I.getType(), TD) &&
4899 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4900 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004901 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004902 Op1C->getOperand(0),
4903 I.getName());
4904 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004905 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004906 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004907 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004908 }
Chris Lattner99c65742007-10-24 05:38:08 +00004909 }
4910
4911
4912 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4913 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4914 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4915 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004916 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004917 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004918 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4919 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4920 // If either of the constants are nans, then the whole thing returns
4921 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004922 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004923 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004924
4925 // Otherwise, no need to compare the two constants, compare the
4926 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004927 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4928 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004929 }
Evan Cheng40300622008-10-14 18:44:08 +00004930 } else {
4931 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4932 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004933 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4934 m_Value(Op0RHS)), *Context) &&
4935 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4936 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004937 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4938 // Swap RHS operands to match LHS.
4939 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4940 std::swap(Op1LHS, Op1RHS);
4941 }
4942 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4943 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4944 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004945 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4946 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004947 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4948 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004949 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004950 else if (Op0CC == FCmpInst::FCMP_FALSE)
4951 return ReplaceInstUsesWith(I, Op1);
4952 else if (Op1CC == FCmpInst::FCMP_FALSE)
4953 return ReplaceInstUsesWith(I, Op0);
4954 bool Op0Ordered;
4955 bool Op1Ordered;
4956 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4957 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4958 if (Op0Ordered == Op1Ordered) {
4959 // If both are ordered or unordered, return a new fcmp with
4960 // or'ed predicates.
4961 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004962 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004963 if (Instruction *I = dyn_cast<Instruction>(RV))
4964 return I;
4965 // Otherwise, it's a constant boolean value...
4966 return ReplaceInstUsesWith(I, RV);
4967 }
4968 }
4969 }
4970 }
Chris Lattner99c65742007-10-24 05:38:08 +00004971 }
4972 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004973
Chris Lattner7e708292002-06-25 16:13:24 +00004974 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004975}
4976
Dan Gohman844731a2008-05-13 00:00:25 +00004977namespace {
4978
Chris Lattnerc317d392004-02-16 01:20:27 +00004979// XorSelf - Implements: X ^ X --> 0
4980struct XorSelf {
4981 Value *RHS;
4982 XorSelf(Value *rhs) : RHS(rhs) {}
4983 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4984 Instruction *apply(BinaryOperator &Xor) const {
4985 return &Xor;
4986 }
4987};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004988
Dan Gohman844731a2008-05-13 00:00:25 +00004989}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004990
Chris Lattner7e708292002-06-25 16:13:24 +00004991Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004992 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004994
Evan Chengd34af782008-03-25 20:07:13 +00004995 if (isa<UndefValue>(Op1)) {
4996 if (isa<UndefValue>(Op0))
4997 // Handle undef ^ undef -> 0 special case. This is a common
4998 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00004999 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005000 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005001 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005002
Chris Lattnerc317d392004-02-16 01:20:27 +00005003 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005004 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005005 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005006 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005007 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005008
5009 // See if we can simplify any instructions used by the instruction whose sole
5010 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005011 if (SimplifyDemandedInstructionBits(I))
5012 return &I;
5013 if (isa<VectorType>(I.getType()))
5014 if (isa<ConstantAggregateZero>(Op1))
5015 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005016
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005017 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005018 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005019 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5020 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5021 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5022 if (Op0I->getOpcode() == Instruction::And ||
5023 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005024 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5025 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005026 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005027 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005028 Op0I->getOperand(1)->getName()+".not");
5029 InsertNewInstBefore(NotY, I);
5030 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005031 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005032 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005033 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005034 }
5035 }
5036 }
5037 }
5038
5039
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005040 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005041 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005042 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005043 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005044 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005045 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005046
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005047 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005048 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005049 FCI->getOperand(0), FCI->getOperand(1));
5050 }
5051
Nick Lewycky517e1f52008-05-31 19:01:33 +00005052 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5053 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5054 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5055 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5056 Instruction::CastOps Opcode = Op0C->getOpcode();
5057 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005058 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005059 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005060 Op0C->getDestTy())) {
5061 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005062 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005063 CI->getOpcode(), CI->getInversePredicate(),
5064 CI->getOperand(0), CI->getOperand(1)), I);
5065 NewCI->takeName(CI);
5066 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5067 }
5068 }
5069 }
5070 }
5071 }
5072
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005074 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005075 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5076 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005077 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5078 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5079 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005080 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005081 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005082
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005083 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005084 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005085 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005086 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005087 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005088 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005089 Context->getConstantExprSub(NegOp0CI,
5090 Context->getConstantInt(I.getType(), 1)),
5091 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005092 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005093 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005094 Constant *C =
5095 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005096 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005097
Chris Lattner7c4049c2004-01-12 19:35:11 +00005098 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005099 } else if (Op0I->getOpcode() == Instruction::Or) {
5100 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005101 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005102 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005103 // Anything in both C1 and C2 is known to be zero, remove it from
5104 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005105 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5106 NewRHS = Context->getConstantExprAnd(NewRHS,
5107 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005108 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005109 I.setOperand(0, Op0I->getOperand(0));
5110 I.setOperand(1, NewRHS);
5111 return &I;
5112 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005113 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005114 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005115 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005116
5117 // Try to fold constant and into select arguments.
5118 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005119 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005120 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005121 if (isa<PHINode>(Op0))
5122 if (Instruction *NV = FoldOpIntoPhi(I))
5123 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005124 }
5125
Owen Andersond672ecb2009-07-03 00:17:18 +00005126 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005127 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005128 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005129
Owen Andersond672ecb2009-07-03 00:17:18 +00005130 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005131 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005132 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005133
Chris Lattner318bf792007-03-18 22:51:34 +00005134
5135 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5136 if (Op1I) {
5137 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005138 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005139 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005140 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005141 I.swapOperands();
5142 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005143 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005144 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005145 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005146 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005147 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005148 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005149 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005150 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005151 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5152 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005153 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005154 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005155 std::swap(A, B);
5156 }
Chris Lattner318bf792007-03-18 22:51:34 +00005157 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005158 I.swapOperands(); // Simplified below.
5159 std::swap(Op0, Op1);
5160 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005161 }
Chris Lattner318bf792007-03-18 22:51:34 +00005162 }
5163
5164 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5165 if (Op0I) {
5166 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005167 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5168 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005169 if (A == Op1) // (B|A)^B == (A|B)^B
5170 std::swap(A, B);
5171 if (B == Op1) { // (A|B)^B == A & ~B
5172 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005173 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5174 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005175 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005176 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005178 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005180 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005181 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5182 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005183 if (A == Op1) // (A&B)^A -> (B&A)^A
5184 std::swap(A, B);
5185 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005186 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005187 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005188 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005189 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005190 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005191 }
Chris Lattner318bf792007-03-18 22:51:34 +00005192 }
5193
5194 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5195 if (Op0I && Op1I && Op0I->isShift() &&
5196 Op0I->getOpcode() == Op1I->getOpcode() &&
5197 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5198 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5199 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005200 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005201 Op1I->getOperand(0),
5202 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005203 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005204 Op1I->getOperand(1));
5205 }
5206
5207 if (Op0I && Op1I) {
5208 Value *A, *B, *C, *D;
5209 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5211 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005212 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005213 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005214 }
5215 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005216 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5217 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005218 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005219 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005220 }
5221
5222 // (A & B)^(C & D)
5223 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005224 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5225 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005226 // (X & Y)^(X & Y) -> (Y^Z) & X
5227 Value *X = 0, *Y = 0, *Z = 0;
5228 if (A == C)
5229 X = A, Y = B, Z = D;
5230 else if (A == D)
5231 X = A, Y = B, Z = C;
5232 else if (B == C)
5233 X = B, Y = A, Z = D;
5234 else if (B == D)
5235 X = B, Y = A, Z = C;
5236
5237 if (X) {
5238 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005239 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5240 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005241 }
5242 }
5243 }
5244
Reid Spencere4d87aa2006-12-23 06:05:41 +00005245 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5246 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005247 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005248 return R;
5249
Chris Lattner6fc205f2006-05-05 06:39:07 +00005250 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5254 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005255 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005256 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005257 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5258 I.getType(), TD) &&
5259 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5260 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005261 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005262 Op1C->getOperand(0),
5263 I.getName());
5264 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005266 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005267 }
Chris Lattner99c65742007-10-24 05:38:08 +00005268 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005269
Chris Lattner7e708292002-06-25 16:13:24 +00005270 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005271}
5272
Owen Andersond672ecb2009-07-03 00:17:18 +00005273static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005274 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005275 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005276}
Chris Lattnera96879a2004-09-29 17:40:11 +00005277
Dan Gohman6de29f82009-06-15 22:12:54 +00005278static bool HasAddOverflow(ConstantInt *Result,
5279 ConstantInt *In1, ConstantInt *In2,
5280 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005281 if (IsSigned)
5282 if (In2->getValue().isNegative())
5283 return Result->getValue().sgt(In1->getValue());
5284 else
5285 return Result->getValue().slt(In1->getValue());
5286 else
5287 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005288}
5289
Dan Gohman6de29f82009-06-15 22:12:54 +00005290/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005291/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005292static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005293 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005294 bool IsSigned = false) {
5295 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005296
Dan Gohman6de29f82009-06-15 22:12:54 +00005297 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005299 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5300 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301 ExtractElement(In1, Idx, Context),
5302 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005303 IsSigned))
5304 return true;
5305 }
5306 return false;
5307 }
5308
5309 return HasAddOverflow(cast<ConstantInt>(Result),
5310 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5311 IsSigned);
5312}
5313
5314static bool HasSubOverflow(ConstantInt *Result,
5315 ConstantInt *In1, ConstantInt *In2,
5316 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005317 if (IsSigned)
5318 if (In2->getValue().isNegative())
5319 return Result->getValue().slt(In1->getValue());
5320 else
5321 return Result->getValue().sgt(In1->getValue());
5322 else
5323 return Result->getValue().ugt(In1->getValue());
5324}
5325
Dan Gohman6de29f82009-06-15 22:12:54 +00005326/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327/// overflowed for this type.
5328static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005329 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005330 bool IsSigned = false) {
5331 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005332
5333 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005335 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5336 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337 ExtractElement(In1, Idx, Context),
5338 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005339 IsSigned))
5340 return true;
5341 }
5342 return false;
5343 }
5344
5345 return HasSubOverflow(cast<ConstantInt>(Result),
5346 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347 IsSigned);
5348}
5349
Chris Lattner574da9b2005-01-13 20:14:25 +00005350/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351/// code necessary to compute the offset from the base pointer (without adding
5352/// in the base pointer). Return the result as a signed integer of intptr size.
5353static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005354 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005355 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005357 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005358 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005359
5360 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005361 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005362 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005363
Gabor Greif177dd3f2008-06-12 21:37:33 +00005364 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5365 ++i, ++GTI) {
5366 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005367 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005368 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369 if (OpC->isZero()) continue;
5370
5371 // Handle a struct index, which adds its field offset to the pointer.
5372 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374
5375 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005376 Result =
5377 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005378 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005379 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005380 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005381 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005382 GEP->getName()+".offs"), I);
5383 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005384 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005385
Owen Andersond672ecb2009-07-03 00:17:18 +00005386 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5387 Constant *OC =
5388 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5389 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005390 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005391 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 else {
5393 // Emit an add instruction.
5394 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005395 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005396 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005397 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005398 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005399 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005400 // Convert to correct type.
5401 if (Op->getType() != IntPtrTy) {
5402 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005403 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005404 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005405 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5406 true,
5407 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 }
5409 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005410 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005411 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005412 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005414 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 GEP->getName()+".idx"), I);
5416 }
5417
5418 // Emit an add instruction.
5419 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005420 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 cast<Constant>(Result));
5422 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005423 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005424 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005425 }
5426 return Result;
5427}
5428
Chris Lattner10c0d912008-04-22 02:53:33 +00005429
Dan Gohman8f080f02009-07-17 22:16:21 +00005430/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5431/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5432/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5433/// be complex, and scales are involved. The above expression would also be
5434/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5435/// This later form is less amenable to optimization though, and we are allowed
5436/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005437///
5438/// If we can't emit an optimized form for this expression, this returns null.
5439///
5440static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5441 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005442 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005443 gep_type_iterator GTI = gep_type_begin(GEP);
5444
5445 // Check to see if this gep only has a single variable index. If so, and if
5446 // any constant indices are a multiple of its scale, then we can compute this
5447 // in terms of the scale of the variable index. For example, if the GEP
5448 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5449 // because the expression will cross zero at the same point.
5450 unsigned i, e = GEP->getNumOperands();
5451 int64_t Offset = 0;
5452 for (i = 1; i != e; ++i, ++GTI) {
5453 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5454 // Compute the aggregate offset of constant indices.
5455 if (CI->isZero()) continue;
5456
5457 // Handle a struct index, which adds its field offset to the pointer.
5458 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5459 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5460 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005461 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005462 Offset += Size*CI->getSExtValue();
5463 }
5464 } else {
5465 // Found our variable index.
5466 break;
5467 }
5468 }
5469
5470 // If there are no variable indices, we must have a constant offset, just
5471 // evaluate it the general way.
5472 if (i == e) return 0;
5473
5474 Value *VariableIdx = GEP->getOperand(i);
5475 // Determine the scale factor of the variable element. For example, this is
5476 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005477 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005478
5479 // Verify that there are no other variable indices. If so, emit the hard way.
5480 for (++i, ++GTI; i != e; ++i, ++GTI) {
5481 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5482 if (!CI) return 0;
5483
5484 // Compute the aggregate offset of constant indices.
5485 if (CI->isZero()) continue;
5486
5487 // Handle a struct index, which adds its field offset to the pointer.
5488 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5489 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5490 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005491 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005492 Offset += Size*CI->getSExtValue();
5493 }
5494 }
5495
5496 // Okay, we know we have a single variable index, which must be a
5497 // pointer/array/vector index. If there is no offset, life is simple, return
5498 // the index.
5499 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5500 if (Offset == 0) {
5501 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5502 // we don't need to bother extending: the extension won't affect where the
5503 // computation crosses zero.
5504 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5505 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5506 VariableIdx->getNameStart(), &I);
5507 return VariableIdx;
5508 }
5509
5510 // Otherwise, there is an index. The computation we will do will be modulo
5511 // the pointer size, so get it.
5512 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5513
5514 Offset &= PtrSizeMask;
5515 VariableScale &= PtrSizeMask;
5516
5517 // To do this transformation, any constant index must be a multiple of the
5518 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5519 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5520 // multiple of the variable scale.
5521 int64_t NewOffs = Offset / (int64_t)VariableScale;
5522 if (Offset != NewOffs*(int64_t)VariableScale)
5523 return 0;
5524
5525 // Okay, we can do this evaluation. Start by converting the index to intptr.
5526 const Type *IntPtrTy = TD.getIntPtrType();
5527 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005528 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005529 true /*SExt*/,
5530 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005531 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005532 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005533}
5534
5535
Reid Spencere4d87aa2006-12-23 06:05:41 +00005536/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005537/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005538Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5539 ICmpInst::Predicate Cond,
5540 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005541 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005542
Chris Lattner10c0d912008-04-22 02:53:33 +00005543 // Look through bitcasts.
5544 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5545 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005546
Chris Lattner574da9b2005-01-13 20:14:25 +00005547 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005548 if (TD && PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005549 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005550 // This transformation (ignoring the base and scales) is valid because we
5551 // know pointers can't overflow. See if we can output an optimized form.
5552 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5553
5554 // If not, synthesize the offset the hard way.
5555 if (Offset == 0)
5556 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005557 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005558 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005559 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005560 // If the base pointers are different, but the indices are the same, just
5561 // compare the base pointer.
5562 if (PtrBase != GEPRHS->getOperand(0)) {
5563 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005564 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005565 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005566 if (IndicesTheSame)
5567 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5568 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5569 IndicesTheSame = false;
5570 break;
5571 }
5572
5573 // If all indices are the same, just compare the base pointers.
5574 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005575 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005576 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005577
5578 // Otherwise, the base pointers are different and the indices are
5579 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005580 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005581 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005582
Chris Lattnere9d782b2005-01-13 22:25:21 +00005583 // If one of the GEPs has all zero indices, recurse.
5584 bool AllZeros = true;
5585 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5586 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5587 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5588 AllZeros = false;
5589 break;
5590 }
5591 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005592 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5593 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005594
5595 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005596 AllZeros = true;
5597 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5598 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5599 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5600 AllZeros = false;
5601 break;
5602 }
5603 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005604 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005605
Chris Lattner4401c9c2005-01-14 00:20:05 +00005606 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5607 // If the GEPs only differ by one index, compare it.
5608 unsigned NumDifferences = 0; // Keep track of # differences.
5609 unsigned DiffOperand = 0; // The operand that differs.
5610 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005612 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5613 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005614 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005615 NumDifferences = 2;
5616 break;
5617 } else {
5618 if (NumDifferences++) break;
5619 DiffOperand = i;
5620 }
5621 }
5622
5623 if (NumDifferences == 0) // SAME GEP?
5624 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005625 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005626 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005627
Chris Lattner4401c9c2005-01-14 00:20:05 +00005628 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005629 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5630 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005631 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005632 return new ICmpInst(*Context,
5633 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005634 }
5635 }
5636
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005638 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005639 if (TD &&
5640 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005641 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5642 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5643 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5644 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005645 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005646 }
5647 }
5648 return 0;
5649}
5650
Chris Lattnera5406232008-05-19 20:18:56 +00005651/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5652///
5653Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5654 Instruction *LHSI,
5655 Constant *RHSC) {
5656 if (!isa<ConstantFP>(RHSC)) return 0;
5657 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5658
5659 // Get the width of the mantissa. We don't want to hack on conversions that
5660 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005661 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005662 if (MantissaWidth == -1) return 0; // Unknown.
5663
5664 // Check to see that the input is converted from an integer type that is small
5665 // enough that preserves all bits. TODO: check here for "known" sign bits.
5666 // 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 +00005667 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005668
5669 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005670 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5671 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005672 ++InputSize;
5673
5674 // If the conversion would lose info, don't hack on this.
5675 if ((int)InputSize > MantissaWidth)
5676 return 0;
5677
5678 // Otherwise, we can potentially simplify the comparison. We know that it
5679 // will always come through as an integer value and we know the constant is
5680 // not a NAN (it would have been previously simplified).
5681 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5682
5683 ICmpInst::Predicate Pred;
5684 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005685 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005686 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005687 case FCmpInst::FCMP_OEQ:
5688 Pred = ICmpInst::ICMP_EQ;
5689 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005690 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005691 case FCmpInst::FCMP_OGT:
5692 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5693 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005694 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005695 case FCmpInst::FCMP_OGE:
5696 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5697 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005698 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 case FCmpInst::FCMP_OLT:
5700 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5701 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005702 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 case FCmpInst::FCMP_OLE:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5705 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005706 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005707 case FCmpInst::FCMP_ONE:
5708 Pred = ICmpInst::ICMP_NE;
5709 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005710 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005711 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005713 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005714 }
5715
5716 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5717
5718 // Now we know that the APFloat is a normal number, zero or inf.
5719
Chris Lattner85162782008-05-20 03:50:52 +00005720 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005721 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005722 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005723
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005724 if (!LHSUnsigned) {
5725 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5726 // and large values.
5727 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5728 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5729 APFloat::rmNearestTiesToEven);
5730 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5731 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5732 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005733 return ReplaceInstUsesWith(I, Context->getTrue());
5734 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005735 }
5736 } else {
5737 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5738 // +INF and large values.
5739 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5740 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5741 APFloat::rmNearestTiesToEven);
5742 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5743 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5744 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005745 return ReplaceInstUsesWith(I, Context->getTrue());
5746 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005747 }
Chris Lattnera5406232008-05-19 20:18:56 +00005748 }
5749
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 if (!LHSUnsigned) {
5751 // See if the RHS value is < SignedMin.
5752 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5753 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5754 APFloat::rmNearestTiesToEven);
5755 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5756 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5757 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005758 return ReplaceInstUsesWith(I, Context->getTrue());
5759 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005760 }
Chris Lattnera5406232008-05-19 20:18:56 +00005761 }
5762
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005763 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5764 // [0, UMAX], but it may still be fractional. See if it is fractional by
5765 // casting the FP value to the integer value and back, checking for equality.
5766 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005767 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005768 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5769 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005770 if (!RHS.isZero()) {
5771 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005772 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5773 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005774 if (!Equal) {
5775 // If we had a comparison against a fractional value, we have to adjust
5776 // the compare predicate and sometimes the value. RHSC is rounded towards
5777 // zero at this point.
5778 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005779 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005780 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005781 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005782 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005783 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005784 case ICmpInst::ICMP_ULE:
5785 // (float)int <= 4.4 --> int <= 4
5786 // (float)int <= -4.4 --> false
5787 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005788 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005789 break;
5790 case ICmpInst::ICMP_SLE:
5791 // (float)int <= 4.4 --> int <= 4
5792 // (float)int <= -4.4 --> int < -4
5793 if (RHS.isNegative())
5794 Pred = ICmpInst::ICMP_SLT;
5795 break;
5796 case ICmpInst::ICMP_ULT:
5797 // (float)int < -4.4 --> false
5798 // (float)int < 4.4 --> int <= 4
5799 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005800 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005801 Pred = ICmpInst::ICMP_ULE;
5802 break;
5803 case ICmpInst::ICMP_SLT:
5804 // (float)int < -4.4 --> int < -4
5805 // (float)int < 4.4 --> int <= 4
5806 if (!RHS.isNegative())
5807 Pred = ICmpInst::ICMP_SLE;
5808 break;
5809 case ICmpInst::ICMP_UGT:
5810 // (float)int > 4.4 --> int > 4
5811 // (float)int > -4.4 --> true
5812 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005813 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005814 break;
5815 case ICmpInst::ICMP_SGT:
5816 // (float)int > 4.4 --> int > 4
5817 // (float)int > -4.4 --> int >= -4
5818 if (RHS.isNegative())
5819 Pred = ICmpInst::ICMP_SGE;
5820 break;
5821 case ICmpInst::ICMP_UGE:
5822 // (float)int >= -4.4 --> true
5823 // (float)int >= 4.4 --> int > 4
5824 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005825 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005826 Pred = ICmpInst::ICMP_UGT;
5827 break;
5828 case ICmpInst::ICMP_SGE:
5829 // (float)int >= -4.4 --> int >= -4
5830 // (float)int >= 4.4 --> int > 4
5831 if (!RHS.isNegative())
5832 Pred = ICmpInst::ICMP_SGT;
5833 break;
5834 }
Chris Lattnera5406232008-05-19 20:18:56 +00005835 }
5836 }
5837
5838 // Lower this FP comparison into an appropriate integer version of the
5839 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005840 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005841}
5842
Reid Spencere4d87aa2006-12-23 06:05:41 +00005843Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5844 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005846
Chris Lattner58e97462007-01-14 19:42:17 +00005847 // Fold trivial predicates.
5848 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005849 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005850 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005851 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005852
5853 // Simplify 'fcmp pred X, X'
5854 if (Op0 == Op1) {
5855 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005856 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005857 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5858 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5859 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005860 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005861 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5862 case FCmpInst::FCMP_OLT: // True if ordered and less than
5863 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005864 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005865
5866 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5867 case FCmpInst::FCMP_ULT: // True if unordered or less than
5868 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5869 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5870 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5871 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005872 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005873 return &I;
5874
5875 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5876 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5877 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5878 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5879 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5880 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005881 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005882 return &I;
5883 }
5884 }
5885
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005887 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005888
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 // Handle fcmp with constant RHS
5890 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005891 // If the constant is a nan, see if we can fold the comparison based on it.
5892 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5893 if (CFP->getValueAPF().isNaN()) {
5894 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005895 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005896 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5897 "Comparison must be either ordered or unordered!");
5898 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005899 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005900 }
5901 }
5902
Reid Spencere4d87aa2006-12-23 06:05:41 +00005903 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5904 switch (LHSI->getOpcode()) {
5905 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005906 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5907 // block. If in the same block, we're encouraging jump threading. If
5908 // not, we are just pessimizing the code by making an i1 phi.
5909 if (LHSI->getParent() == I.getParent())
5910 if (Instruction *NV = FoldOpIntoPhi(I))
5911 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005913 case Instruction::SIToFP:
5914 case Instruction::UIToFP:
5915 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5916 return NV;
5917 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005918 case Instruction::Select:
5919 // If either operand of the select is a constant, we can fold the
5920 // comparison into the select arms, which will cause one to be
5921 // constant folded and the select turned into a bitwise or.
5922 Value *Op1 = 0, *Op2 = 0;
5923 if (LHSI->hasOneUse()) {
5924 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5925 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005926 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005927 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005928 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 LHSI->getOperand(2), RHSC,
5930 I.getName()), I);
5931 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5932 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005933 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005935 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936 LHSI->getOperand(1), RHSC,
5937 I.getName()), I);
5938 }
5939 }
5940
5941 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005942 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005943 break;
5944 }
5945 }
5946
5947 return Changed ? &I : 0;
5948}
5949
5950Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5951 bool Changed = SimplifyCompare(I);
5952 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5953 const Type *Ty = Op0->getType();
5954
5955 // icmp X, X
5956 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005957 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005958 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959
5960 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005961 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005962
Reid Spencere4d87aa2006-12-23 06:05:41 +00005963 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005964 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005965 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5966 isa<ConstantPointerNull>(Op0)) &&
5967 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005968 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005969 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005970 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005971
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005973 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005975 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005976 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005977 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005978 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00005979 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005980 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005981 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005982 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005983
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005985 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005986 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005987 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00005988 Instruction *Not = BinaryOperator::CreateNot(*Context,
5989 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005990 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005991 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005992 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005993 case ICmpInst::ICMP_SGT:
5994 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005995 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005996 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00005997 Instruction *Not = BinaryOperator::CreateNot(*Context,
5998 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005999 InsertNewInstBefore(Not, I);
6000 return BinaryOperator::CreateAnd(Not, Op0);
6001 }
6002 case ICmpInst::ICMP_UGE:
6003 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6004 // FALL THROUGH
6005 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006006 Instruction *Not = BinaryOperator::CreateNot(*Context,
6007 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006008 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006009 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006010 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 case ICmpInst::ICMP_SGE:
6012 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6013 // FALL THROUGH
6014 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006015 Instruction *Not = BinaryOperator::CreateNot(*Context,
6016 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 InsertNewInstBefore(Not, I);
6018 return BinaryOperator::CreateOr(Not, Op0);
6019 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 }
Chris Lattner8b170942002-08-09 23:47:40 +00006021 }
6022
Dan Gohman1c8491e2009-04-25 17:12:48 +00006023 unsigned BitWidth = 0;
6024 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006025 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6026 else if (Ty->isIntOrIntVector())
6027 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006028
6029 bool isSignBit = false;
6030
Dan Gohman81b28ce2008-09-16 18:46:06 +00006031 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006032 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006033 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006034
Chris Lattnerb6566012008-01-05 01:18:20 +00006035 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6036 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006037 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006038 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006039 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006040 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006041
Dan Gohman81b28ce2008-09-16 18:46:06 +00006042 // If we have an icmp le or icmp ge instruction, turn it into the
6043 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6044 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006045 switch (I.getPredicate()) {
6046 default: break;
6047 case ICmpInst::ICMP_ULE:
6048 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006049 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006050 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6051 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006052 case ICmpInst::ICMP_SLE:
6053 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006054 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006055 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6056 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006057 case ICmpInst::ICMP_UGE:
6058 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006059 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006060 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6061 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006062 case ICmpInst::ICMP_SGE:
6063 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006064 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006065 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6066 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006067 }
6068
Chris Lattner183661e2008-07-11 05:40:05 +00006069 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006070 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006071 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006072 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6073 }
6074
6075 // See if we can fold the comparison based on range information we can get
6076 // by checking whether bits are known to be zero or one in the input.
6077 if (BitWidth != 0) {
6078 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6079 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6080
6081 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006082 isSignBit ? APInt::getSignBit(BitWidth)
6083 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006085 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (SimplifyDemandedBits(I.getOperandUse(1),
6087 APInt::getAllOnesValue(BitWidth),
6088 Op1KnownZero, Op1KnownOne, 0))
6089 return &I;
6090
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006091 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006092 // in. Compute the Min, Max and RHS values based on the known bits. For the
6093 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6095 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6096 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6097 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6098 Op0Min, Op0Max);
6099 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6100 Op1Min, Op1Max);
6101 } else {
6102 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6103 Op0Min, Op0Max);
6104 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6105 Op1Min, Op1Max);
6106 }
6107
Chris Lattner183661e2008-07-11 05:40:05 +00006108 // If Min and Max are known to be the same, then SimplifyDemandedBits
6109 // figured out that the LHS is a constant. Just constant fold this now so
6110 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006111 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006112 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006113 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006115 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006116 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117
Chris Lattner183661e2008-07-11 05:40:05 +00006118 // Based on the range information we know about the LHS, see if we can
6119 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006121 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006122 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006124 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006125 break;
6126 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006128 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006129 break;
6130 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006131 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006132 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006134 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006136 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6138 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006139 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6140 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141
6142 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6143 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006144 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006145 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 }
Chris Lattner84dff672008-07-11 05:08:55 +00006147 break;
6148 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006150 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006152 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153
6154 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006155 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006156 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6157 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006158 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6159 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006160
6161 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6162 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006163 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006164 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 }
Chris Lattner84dff672008-07-11 05:08:55 +00006166 break;
6167 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006169 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006171 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 }
Chris Lattner84dff672008-07-11 05:08:55 +00006179 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 case ICmpInst::ICMP_SGT:
6181 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006182 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006184 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185
6186 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006187 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006190 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 }
6193 break;
6194 case ICmpInst::ICMP_SGE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6196 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006197 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006199 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 break;
6201 case ICmpInst::ICMP_SLE:
6202 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6203 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006204 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006206 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 break;
6208 case ICmpInst::ICMP_UGE:
6209 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6210 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006211 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006213 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 break;
6215 case ICmpInst::ICMP_ULE:
6216 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6217 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006218 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006220 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006221 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006222 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223
6224 // Turn a signed comparison into an unsigned one if both operands
6225 // are known to have the same sign.
6226 if (I.isSignedPredicate() &&
6227 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6228 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006229 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006230 }
6231
6232 // Test if the ICmpInst instruction is used exclusively by a select as
6233 // part of a minimum or maximum operation. If so, refrain from doing
6234 // any other folding. This helps out other analyses which understand
6235 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6236 // and CodeGen. And in this case, at least one of the comparison
6237 // operands has at least one user besides the compare (the select),
6238 // which would often largely negate the benefit of folding anyway.
6239 if (I.hasOneUse())
6240 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6241 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6242 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6243 return 0;
6244
6245 // See if we are doing a comparison between a constant and an instruction that
6246 // can be folded into the comparison.
6247 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006249 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006250 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006252 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6253 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006254 }
6255
Chris Lattner01deb9d2007-04-03 17:43:25 +00006256 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006257 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6258 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6259 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006260 case Instruction::GetElementPtr:
6261 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006263 bool isAllZeros = true;
6264 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6265 if (!isa<Constant>(LHSI->getOperand(i)) ||
6266 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6267 isAllZeros = false;
6268 break;
6269 }
6270 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006271 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006272 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006273 }
6274 break;
6275
Chris Lattner6970b662005-04-23 15:31:55 +00006276 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006277 // Only fold icmp into the PHI if the phi and fcmp are in the same
6278 // block. If in the same block, we're encouraging jump threading. If
6279 // not, we are just pessimizing the code by making an i1 phi.
6280 if (LHSI->getParent() == I.getParent())
6281 if (Instruction *NV = FoldOpIntoPhi(I))
6282 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006283 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006284 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006285 // If either operand of the select is a constant, we can fold the
6286 // comparison into the select arms, which will cause one to be
6287 // constant folded and the select turned into a bitwise or.
6288 Value *Op1 = 0, *Op2 = 0;
6289 if (LHSI->hasOneUse()) {
6290 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6291 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006292 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006294 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 LHSI->getOperand(2), RHSC,
6296 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006297 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6298 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006299 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006300 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006301 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006302 LHSI->getOperand(1), RHSC,
6303 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006304 }
6305 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006306
Chris Lattner6970b662005-04-23 15:31:55 +00006307 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006308 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006309 break;
6310 }
Chris Lattner4802d902007-04-06 18:57:34 +00006311 case Instruction::Malloc:
6312 // If we have (malloc != null), and if the malloc has a single use, we
6313 // can assume it is successful and remove the malloc.
6314 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6315 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006316 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006317 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006318 }
6319 break;
6320 }
Chris Lattner6970b662005-04-23 15:31:55 +00006321 }
6322
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006324 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006326 return NI;
6327 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6329 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006330 return NI;
6331
Reid Spencere4d87aa2006-12-23 06:05:41 +00006332 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006333 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6334 // now.
6335 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6336 if (isa<PointerType>(Op0->getType()) &&
6337 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006338 // We keep moving the cast from the left operand over to the right
6339 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006340 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006341
Chris Lattner57d86372007-01-06 01:45:59 +00006342 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6343 // so eliminate it as well.
6344 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6345 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006346
Chris Lattnerde90b762003-11-03 04:25:02 +00006347 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006348 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006349 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006350 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006351 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006353 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006354 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006355 }
Owen Anderson333c4002009-07-09 23:48:35 +00006356 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006357 }
Chris Lattner57d86372007-01-06 01:45:59 +00006358 }
6359
6360 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006361 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006362 // This comes up when you have code like
6363 // int X = A < B;
6364 // if (X) ...
6365 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006366 // with a constant or another cast from the same type.
6367 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006368 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006369 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006370 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006371
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006372 // See if it's the same type of instruction on the left and right.
6373 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6374 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006375 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006376 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006377 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006378 default: break;
6379 case Instruction::Add:
6380 case Instruction::Sub:
6381 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006382 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006383 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006384 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006385 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6386 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6387 if (CI->getValue().isSignBit()) {
6388 ICmpInst::Predicate Pred = I.isSignedPredicate()
6389 ? I.getUnsignedPredicate()
6390 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006391 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006392 Op1I->getOperand(0));
6393 }
6394
6395 if (CI->getValue().isMaxSignedValue()) {
6396 ICmpInst::Predicate Pred = I.isSignedPredicate()
6397 ? I.getUnsignedPredicate()
6398 : I.getSignedPredicate();
6399 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006400 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006401 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006402 }
6403 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006404 break;
6405 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006406 if (!I.isEquality())
6407 break;
6408
Nick Lewycky5d52c452008-08-21 05:56:10 +00006409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6410 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6411 // Mask = -1 >> count-trailing-zeros(Cst).
6412 if (!CI->isZero() && !CI->isOne()) {
6413 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006414 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006415 APInt::getLowBitsSet(AP.getBitWidth(),
6416 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006417 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006418 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6419 Mask);
6420 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6421 Mask);
6422 InsertNewInstBefore(And1, I);
6423 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006424 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006425 }
6426 }
6427 break;
6428 }
6429 }
6430 }
6431 }
6432
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006433 // ~x < ~y --> y < x
6434 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006435 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6436 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006437 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006438 }
6439
Chris Lattner65b72ba2006-09-18 04:22:48 +00006440 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006441 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006442
6443 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006444 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6445 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006446 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006447
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006448 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006449 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6450 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006451 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006452 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006453 }
6454
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006455 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006456 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006457 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006458 if (match(B, m_ConstantInt(C1), *Context) &&
6459 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006460 Constant *NC =
6461 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006462 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006463 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006464 InsertNewInstBefore(Xor, I));
6465 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006466
6467 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006468 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6469 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6470 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6471 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006472 }
6473 }
6474
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006475 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006476 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006477 // A == (A^B) -> B == 0
6478 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006479 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006480 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006481 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006482
6483 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006484 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006485 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006486 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006487
6488 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006489 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006490 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006491 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006492
Chris Lattner9c2328e2006-11-14 06:06:06 +00006493 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6494 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006495 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6496 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006497 Value *X = 0, *Y = 0, *Z = 0;
6498
6499 if (A == C) {
6500 X = B; Y = D; Z = A;
6501 } else if (A == D) {
6502 X = B; Y = C; Z = A;
6503 } else if (B == C) {
6504 X = A; Y = D; Z = B;
6505 } else if (B == D) {
6506 X = A; Y = C; Z = B;
6507 }
6508
6509 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006510 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6511 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006512 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006513 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006514 return &I;
6515 }
6516 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006517 }
Chris Lattner7e708292002-06-25 16:13:24 +00006518 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006519}
6520
Chris Lattner562ef782007-06-20 23:46:26 +00006521
6522/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6523/// and CmpRHS are both known to be integer constants.
6524Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6525 ConstantInt *DivRHS) {
6526 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6527 const APInt &CmpRHSV = CmpRHS->getValue();
6528
6529 // FIXME: If the operand types don't match the type of the divide
6530 // then don't attempt this transform. The code below doesn't have the
6531 // logic to deal with a signed divide and an unsigned compare (and
6532 // vice versa). This is because (x /s C1) <s C2 produces different
6533 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6534 // (x /u C1) <u C2. Simply casting the operands and result won't
6535 // work. :( The if statement below tests that condition and bails
6536 // if it finds it.
6537 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6538 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6539 return 0;
6540 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006541 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006542 if (DivIsSigned && DivRHS->isAllOnesValue())
6543 return 0; // The overflow computation also screws up here
6544 if (DivRHS->isOne())
6545 return 0; // Not worth bothering, and eliminates some funny cases
6546 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006547
6548 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6549 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6550 // C2 (CI). By solving for X we can turn this into a range check
6551 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006552 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006553
6554 // Determine if the product overflows by seeing if the product is
6555 // not equal to the divide. Make sure we do the same kind of divide
6556 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006557 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6558 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006559
6560 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006562
Chris Lattner1dbfd482007-06-21 18:11:19 +00006563 // Figure out the interval that is being checked. For example, a comparison
6564 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6565 // Compute this interval based on the constants involved and the signedness of
6566 // the compare/divide. This computes a half-open interval, keeping track of
6567 // whether either value in the interval overflows. After analysis each
6568 // overflow variable is set to 0 if it's corresponding bound variable is valid
6569 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6570 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006571 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572
Chris Lattner562ef782007-06-20 23:46:26 +00006573 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006575 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006576 HiOverflow = LoOverflow = ProdOV;
6577 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006578 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006579 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006580 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006581 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006582 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6583 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006584 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006585 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6587 HiOverflow = LoOverflow = ProdOV;
6588 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006589 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006590 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006592 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006593 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6594 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006595 ConstantInt* DivNeg =
6596 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6597 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006598 true) ? -1 : 0;
6599 }
Chris Lattner562ef782007-06-20 23:46:26 +00006600 }
Dan Gohman76491272008-02-13 22:09:18 +00006601 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006602 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006604 LoBound = AddOne(DivRHS, Context);
6605 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006606 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6607 HiOverflow = 1; // [INTMIN+1, overflow)
6608 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6609 }
Dan Gohman76491272008-02-13 22:09:18 +00006610 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006611 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006612 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006613 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006614 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006615 LoOverflow = AddWithOverflow(LoBound, HiBound,
6616 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006617 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006618 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6619 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006620 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006621 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006622 }
6623
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 // Dividing by a negative swaps the condition. LT <-> GT
6625 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006626 }
6627
6628 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006630 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006631 case ICmpInst::ICMP_EQ:
6632 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006633 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006634 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006635 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006636 ICmpInst::ICMP_UGE, X, LoBound);
6637 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006638 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006639 ICmpInst::ICMP_ULT, X, HiBound);
6640 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006642 case ICmpInst::ICMP_NE:
6643 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006644 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006645 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006646 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006647 ICmpInst::ICMP_ULT, X, LoBound);
6648 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006649 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006650 ICmpInst::ICMP_UGE, X, HiBound);
6651 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006652 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006653 case ICmpInst::ICMP_ULT:
6654 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006656 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006658 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006659 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006660 case ICmpInst::ICMP_UGT:
6661 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006663 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006665 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006668 else
Owen Anderson333c4002009-07-09 23:48:35 +00006669 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 }
6671}
6672
6673
Chris Lattner01deb9d2007-04-03 17:43:25 +00006674/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6675///
6676Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6677 Instruction *LHSI,
6678 ConstantInt *RHS) {
6679 const APInt &RHSV = RHS->getValue();
6680
6681 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006682 case Instruction::Trunc:
6683 if (ICI.isEquality() && LHSI->hasOneUse()) {
6684 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6685 // of the high bits truncated out of x are known.
6686 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6687 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6688 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6689 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6690 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6691
6692 // If all the high bits are known, we can do this xform.
6693 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6694 // Pull in the high bits from known-ones set.
6695 APInt NewRHS(RHS->getValue());
6696 NewRHS.zext(SrcBits);
6697 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006698 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006699 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006700 }
6701 }
6702 break;
6703
Duncan Sands0091bf22007-04-04 06:42:45 +00006704 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006705 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6706 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6707 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006708 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6709 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006710 Value *CompareVal = LHSI->getOperand(0);
6711
6712 // If the sign bit of the XorCST is not set, there is no change to
6713 // the operation, just stop using the Xor.
6714 if (!XorCST->getValue().isNegative()) {
6715 ICI.setOperand(0, CompareVal);
6716 AddToWorkList(LHSI);
6717 return &ICI;
6718 }
6719
6720 // Was the old condition true if the operand is positive?
6721 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6722
6723 // If so, the new one isn't.
6724 isTrueIfPositive ^= true;
6725
6726 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006727 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006728 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006729 else
Owen Anderson333c4002009-07-09 23:48:35 +00006730 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006731 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006732 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006733
6734 if (LHSI->hasOneUse()) {
6735 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6736 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6737 const APInt &SignBit = XorCST->getValue();
6738 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6739 ? ICI.getUnsignedPredicate()
6740 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006741 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006742 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006743 }
6744
6745 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006746 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006747 const APInt &NotSignBit = XorCST->getValue();
6748 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6749 ? ICI.getUnsignedPredicate()
6750 : ICI.getSignedPredicate();
6751 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006752 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006753 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006754 }
6755 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006756 }
6757 break;
6758 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6759 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6760 LHSI->getOperand(0)->hasOneUse()) {
6761 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6762
6763 // If the LHS is an AND of a truncating cast, we can widen the
6764 // and/compare to be the input width without changing the value
6765 // produced, eliminating a cast.
6766 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6767 // We can do this transformation if either the AND constant does not
6768 // have its sign bit set or if it is an equality comparison.
6769 // Extending a relational comparison when we're checking the sign
6770 // bit would not work.
6771 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006772 (ICI.isEquality() ||
6773 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 uint32_t BitWidth =
6775 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6776 APInt NewCST = AndCST->getValue();
6777 NewCST.zext(BitWidth);
6778 APInt NewCI = RHSV;
6779 NewCI.zext(BitWidth);
6780 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006781 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006782 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006783 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006784 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006785 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786 }
6787 }
6788
6789 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6790 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6791 // happens a LOT in code produced by the C front-end, for bitfield
6792 // access.
6793 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6794 if (Shift && !Shift->isShift())
6795 Shift = 0;
6796
6797 ConstantInt *ShAmt;
6798 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6799 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6800 const Type *AndTy = AndCST->getType(); // Type of the and.
6801
6802 // We can fold this as long as we can't shift unknown bits
6803 // into the mask. This can only happen with signed shift
6804 // rights, as they sign-extend.
6805 if (ShAmt) {
6806 bool CanFold = Shift->isLogicalShift();
6807 if (!CanFold) {
6808 // To test for the bad case of the signed shr, see if any
6809 // of the bits shifted in could be tested after the mask.
6810 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6811 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6812
6813 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6814 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6815 AndCST->getValue()) == 0)
6816 CanFold = true;
6817 }
6818
6819 if (CanFold) {
6820 Constant *NewCst;
6821 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006822 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006824 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006825
6826 // Check to see if we are shifting out any of the bits being
6827 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006828 if (Context->getConstantExpr(Shift->getOpcode(),
6829 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006830 // If we shifted bits out, the fold is not going to work out.
6831 // As a special case, check to see if this means that the
6832 // result is always true or false now.
6833 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006834 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006835 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006836 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006837 } else {
6838 ICI.setOperand(1, NewCst);
6839 Constant *NewAndCST;
6840 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006841 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006842 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006843 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 LHSI->setOperand(1, NewAndCST);
6845 LHSI->setOperand(0, Shift->getOperand(0));
6846 AddToWorkList(Shift); // Shift is dead.
6847 AddUsesToWorkList(ICI);
6848 return &ICI;
6849 }
6850 }
6851 }
6852
6853 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6854 // preferable because it allows the C<<Y expression to be hoisted out
6855 // of a loop if Y is invariant and X is not.
6856 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006857 ICI.isEquality() && !Shift->isArithmeticShift() &&
6858 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859 // Compute C << Y.
6860 Value *NS;
6861 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006862 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 Shift->getOperand(1), "tmp");
6864 } else {
6865 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006866 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867 Shift->getOperand(1), "tmp");
6868 }
6869 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6870
6871 // Compute X & (C << Y).
6872 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006873 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006874 InsertNewInstBefore(NewAnd, ICI);
6875
6876 ICI.setOperand(0, NewAnd);
6877 return &ICI;
6878 }
6879 }
6880 break;
6881
Chris Lattnera0141b92007-07-15 20:42:37 +00006882 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6883 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6884 if (!ShAmt) break;
6885
6886 uint32_t TypeBits = RHSV.getBitWidth();
6887
6888 // Check that the shift amount is in range. If not, don't perform
6889 // undefined shifts. When the shift is visited it will be
6890 // simplified.
6891 if (ShAmt->uge(TypeBits))
6892 break;
6893
6894 if (ICI.isEquality()) {
6895 // If we are comparing against bits always shifted out, the
6896 // comparison cannot succeed.
6897 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006898 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6899 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006900 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6901 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006902 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006903 return ReplaceInstUsesWith(ICI, Cst);
6904 }
6905
6906 if (LHSI->hasOneUse()) {
6907 // Otherwise strength reduce the shift into an and.
6908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006910 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6911 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006912
Chris Lattnera0141b92007-07-15 20:42:37 +00006913 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006914 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006915 Mask, LHSI->getName()+".mask");
6916 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006917 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006918 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006919 }
6920 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006921
6922 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6923 bool TrueIfSigned = false;
6924 if (LHSI->hasOneUse() &&
6925 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6926 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006927 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006928 (TypeBits-ShAmt->getZExtValue()-1));
6929 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006930 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006931 Mask, LHSI->getName()+".mask");
6932 Value *And = InsertNewInstBefore(AndI, ICI);
6933
Owen Anderson333c4002009-07-09 23:48:35 +00006934 return new ICmpInst(*Context,
6935 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006936 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006939 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006940
6941 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006942 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006943 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006944 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006945 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006946
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006947 // Check that the shift amount is in range. If not, don't perform
6948 // undefined shifts. When the shift is visited it will be
6949 // simplified.
6950 uint32_t TypeBits = RHSV.getBitWidth();
6951 if (ShAmt->uge(TypeBits))
6952 break;
6953
6954 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006955
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006956 // If we are comparing against bits always shifted out, the
6957 // comparison cannot succeed.
6958 APInt Comp = RHSV << ShAmtVal;
6959 if (LHSI->getOpcode() == Instruction::LShr)
6960 Comp = Comp.lshr(ShAmtVal);
6961 else
6962 Comp = Comp.ashr(ShAmtVal);
6963
6964 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6965 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006966 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006967 return ReplaceInstUsesWith(ICI, Cst);
6968 }
6969
6970 // Otherwise, check to see if the bits shifted out are known to be zero.
6971 // If so, we can compare against the unshifted value:
6972 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006973 if (LHSI->hasOneUse() &&
6974 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006976 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006977 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006978 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006979
Evan Chengf30752c2008-04-23 00:38:06 +00006980 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006981 // Otherwise strength reduce the shift into an and.
6982 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006983 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006984
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006985 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006986 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006987 Mask, LHSI->getName()+".mask");
6988 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006989 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006990 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006991 }
6992 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006993 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006994
6995 case Instruction::SDiv:
6996 case Instruction::UDiv:
6997 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6998 // Fold this div into the comparison, producing a range check.
6999 // Determine, based on the divide type, what the range is being
7000 // checked. If there is an overflow on the low or high side, remember
7001 // it, otherwise compute the range [low, hi) bounding the new value.
7002 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007003 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7004 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7005 DivRHS))
7006 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007007 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007008
7009 case Instruction::Add:
7010 // Fold: icmp pred (add, X, C1), C2
7011
7012 if (!ICI.isEquality()) {
7013 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7014 if (!LHSC) break;
7015 const APInt &LHSV = LHSC->getValue();
7016
7017 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7018 .subtract(LHSV);
7019
7020 if (ICI.isSignedPredicate()) {
7021 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007022 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007023 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007024 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007025 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007026 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007027 }
7028 } else {
7029 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007030 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007031 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007032 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007033 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007034 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007035 }
7036 }
7037 }
7038 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039 }
7040
7041 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7042 if (ICI.isEquality()) {
7043 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7044
7045 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7046 // the second operand is a constant, simplify a bit.
7047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7048 switch (BO->getOpcode()) {
7049 case Instruction::SRem:
7050 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7051 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7052 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7053 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7054 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007055 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007056 BO->getName());
7057 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007059 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007060 }
7061 }
7062 break;
7063 case Instruction::Add:
7064 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7065 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7066 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007067 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007068 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007069 } else if (RHSV == 0) {
7070 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7071 // efficiently invertible, or if the add has just this one use.
7072 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7073
Owen Andersond672ecb2009-07-03 00:17:18 +00007074 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007075 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007076 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007077 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007079 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007080 InsertNewInstBefore(Neg, ICI);
7081 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007082 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007083 }
7084 }
7085 break;
7086 case Instruction::Xor:
7087 // For the xor case, we can xor two constants together, eliminating
7088 // the explicit xor.
7089 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007090 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007091 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092
7093 // FALLTHROUGH
7094 case Instruction::Sub:
7095 // Replace (([sub|xor] A, B) != 0) with (A != B)
7096 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007097 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 BO->getOperand(1));
7099 break;
7100
7101 case Instruction::Or:
7102 // If bits are being or'd in that are not present in the constant we
7103 // are comparing against, then the comparison could never succeed!
7104 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007105 Constant *NotCI = Context->getConstantExprNot(RHS);
7106 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7107 return ReplaceInstUsesWith(ICI,
7108 Context->getConstantInt(Type::Int1Ty,
7109 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110 }
7111 break;
7112
7113 case Instruction::And:
7114 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7115 // If bits are being compared against that are and'd out, then the
7116 // comparison can never succeed!
7117 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007118 return ReplaceInstUsesWith(ICI,
7119 Context->getConstantInt(Type::Int1Ty,
7120 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007121
7122 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7123 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007124 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007126 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007127
7128 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007129 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007131 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007132 ICmpInst::Predicate pred = isICMP_NE ?
7133 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007134 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007135 }
7136
7137 // ((X & ~7) == 0) --> X < 8
7138 if (RHSV == 0 && isHighOnes(BOC)) {
7139 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007140 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007141 ICmpInst::Predicate pred = isICMP_NE ?
7142 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007143 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144 }
7145 }
7146 default: break;
7147 }
7148 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7149 // Handle icmp {eq|ne} <intrinsic>, intcst.
7150 if (II->getIntrinsicID() == Intrinsic::bswap) {
7151 AddToWorkList(II);
7152 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007153 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154 return &ICI;
7155 }
7156 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007157 }
7158 return 0;
7159}
7160
7161/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7162/// We only handle extending casts so far.
7163///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007164Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7165 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007166 Value *LHSCIOp = LHSCI->getOperand(0);
7167 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007168 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007169 Value *RHSCIOp;
7170
Chris Lattner8c756c12007-05-05 22:41:33 +00007171 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7172 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007173 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7174 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007175 cast<IntegerType>(DestTy)->getBitWidth()) {
7176 Value *RHSOp = 0;
7177 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007178 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007179 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7180 RHSOp = RHSC->getOperand(0);
7181 // If the pointer types don't match, insert a bitcast.
7182 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007183 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007184 }
7185
7186 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007187 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007188 }
7189
7190 // The code below only handles extension cast instructions, so far.
7191 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192 if (LHSCI->getOpcode() != Instruction::ZExt &&
7193 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007194 return 0;
7195
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7197 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007198
Reid Spencere4d87aa2006-12-23 06:05:41 +00007199 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007200 // Not an extension from the same type?
7201 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007202 if (RHSCIOp->getType() != LHSCIOp->getType())
7203 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007204
Nick Lewycky4189a532008-01-28 03:48:02 +00007205 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007206 // and the other is a zext), then we can't handle this.
7207 if (CI->getOpcode() != LHSCI->getOpcode())
7208 return 0;
7209
Nick Lewycky4189a532008-01-28 03:48:02 +00007210 // Deal with equality cases early.
7211 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007212 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007213
7214 // A signed comparison of sign extended values simplifies into a
7215 // signed comparison.
7216 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007217 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007218
7219 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007220 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007221 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007222
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 // If we aren't dealing with a constant on the RHS, exit early
7224 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7225 if (!CI)
7226 return 0;
7227
7228 // Compute the constant that would happen if we truncated to SrcTy then
7229 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007230 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7231 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7232 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007233
7234 // If the re-extended constant didn't change...
7235 if (Res2 == CI) {
7236 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7237 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007238 // %A = sext i16 %X to i32
7239 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007241 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007242 // because %A may have negative value.
7243 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007244 // However, we allow this when the compare is EQ/NE, because they are
7245 // signless.
7246 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007247 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007248 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 }
7250
7251 // The re-extended constant changed so the constant cannot be represented
7252 // in the shorter type. Consequently, we cannot emit a simple comparison.
7253
7254 // First, handle some easy cases. We know the result cannot be equal at this
7255 // point so handle the ICI.isEquality() cases
7256 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007257 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007259 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260
7261 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7262 // should have been folded away previously and not enter in here.
7263 Value *Result;
7264 if (isSignedCmp) {
7265 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007266 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007267 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007269 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 } else {
7271 // We're performing an unsigned comparison.
7272 if (isSignedExt) {
7273 // We're performing an unsigned comp with a sign extended value.
7274 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007275 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007276 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7277 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 } else {
7279 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007280 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007281 }
7282 }
7283
7284 // Finally, return the value computed.
7285 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007286 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007288
7289 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7290 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7291 "ICmp should be folded!");
7292 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007293 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007294 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007295}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007296
Reid Spencer832254e2007-02-02 02:16:23 +00007297Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7298 return commonShiftTransforms(I);
7299}
7300
7301Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7302 return commonShiftTransforms(I);
7303}
7304
7305Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007306 if (Instruction *R = commonShiftTransforms(I))
7307 return R;
7308
7309 Value *Op0 = I.getOperand(0);
7310
7311 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7312 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7313 if (CSI->isAllOnesValue())
7314 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007315
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007316 // See if we can turn a signed shr into an unsigned shr.
7317 if (MaskedValueIsZero(Op0,
7318 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7319 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7320
7321 // Arithmetic shifting an all-sign-bit value is a no-op.
7322 unsigned NumSignBits = ComputeNumSignBits(Op0);
7323 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7324 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007325
Chris Lattner348f6652007-12-06 01:59:46 +00007326 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007327}
7328
7329Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7330 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007332
7333 // shl X, 0 == X and shr X, 0 == X
7334 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007335 if (Op1 == Context->getNullValue(Op1->getType()) ||
7336 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007337 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007338
Reid Spencere4d87aa2006-12-23 06:05:41 +00007339 if (isa<UndefValue>(Op0)) {
7340 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007341 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007342 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007343 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007344 }
7345 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007346 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7347 return ReplaceInstUsesWith(I, Op0);
7348 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007349 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007350 }
7351
Dan Gohman9004c8a2009-05-21 02:28:33 +00007352 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007353 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007354 return &I;
7355
Chris Lattner2eefe512004-04-09 19:05:30 +00007356 // Try to fold constant and into select arguments.
7357 if (isa<Constant>(Op0))
7358 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007359 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007360 return R;
7361
Reid Spencerb83eb642006-10-20 07:07:24 +00007362 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007363 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7364 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007365 return 0;
7366}
7367
Reid Spencerb83eb642006-10-20 07:07:24 +00007368Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007369 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007370 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007371
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007372 // See if we can simplify any instructions used by the instruction whose sole
7373 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007374 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007375
Dan Gohmana119de82009-06-14 23:30:43 +00007376 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7377 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007378 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007379 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007380 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007381 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007382 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007383 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007384 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007385 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007386 }
7387
7388 // ((X*C1) << C2) == (X * (C1 << C2))
7389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7390 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7391 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007392 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007393 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007394
7395 // Try to fold constant and into select arguments.
7396 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7397 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7398 return R;
7399 if (isa<PHINode>(Op0))
7400 if (Instruction *NV = FoldOpIntoPhi(I))
7401 return NV;
7402
Chris Lattner8999dd32007-12-22 09:07:47 +00007403 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7404 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7405 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7406 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7407 // place. Don't try to do this transformation in this case. Also, we
7408 // require that the input operand is a shift-by-constant so that we have
7409 // confidence that the shifts will get folded together. We could do this
7410 // xform in more cases, but it is unlikely to be profitable.
7411 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7412 isa<ConstantInt>(TrOp->getOperand(1))) {
7413 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007414 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007415 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007416 I.getName());
7417 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7418
7419 // For logical shifts, the truncation has the effect of making the high
7420 // part of the register be zeros. Emulate this by inserting an AND to
7421 // clear the top bits as needed. This 'and' will usually be zapped by
7422 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007423 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7424 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007425 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7426
7427 // The mask we constructed says what the trunc would do if occurring
7428 // between the shifts. We want to know the effect *after* the second
7429 // shift. We know that it is a logical shift by a constant, so adjust the
7430 // mask as appropriate.
7431 if (I.getOpcode() == Instruction::Shl)
7432 MaskV <<= Op1->getZExtValue();
7433 else {
7434 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7435 MaskV = MaskV.lshr(Op1->getZExtValue());
7436 }
7437
Owen Andersond672ecb2009-07-03 00:17:18 +00007438 Instruction *And =
7439 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7440 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007441 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7442
7443 // Return the value truncated to the interesting size.
7444 return new TruncInst(And, I.getType());
7445 }
7446 }
7447
Chris Lattner4d5542c2006-01-06 07:12:35 +00007448 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007449 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7450 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7451 Value *V1, *V2;
7452 ConstantInt *CC;
7453 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007454 default: break;
7455 case Instruction::Add:
7456 case Instruction::And:
7457 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007458 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007459 // These operators commute.
7460 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007461 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007462 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7463 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007464 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007465 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007466 Op0BO->getName());
7467 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007468 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007469 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007470 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007471 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007472 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007473 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007474 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007475 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007476
Chris Lattner150f12a2005-09-18 06:30:59 +00007477 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007478 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007479 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007480 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007481 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007482 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007483 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007484 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007485 Op0BO->getOperand(0), Op1,
7486 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007487 InsertNewInstBefore(YS, I); // (Y << C)
7488 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007489 BinaryOperator::CreateAnd(V1,
7490 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007491 V1->getName()+".mask");
7492 InsertNewInstBefore(XM, I); // X & (CC << C)
7493
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007494 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007495 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007496 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007497
Reid Spencera07cb7d2007-02-02 14:41:37 +00007498 // FALL THROUGH.
7499 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007500 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007501 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007502 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7503 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007504 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007505 Op0BO->getOperand(1), Op1,
7506 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007507 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007508 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007509 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007510 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007511 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007512 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007513 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007514 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007515 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007516
Chris Lattner13d4ab42006-05-31 21:14:00 +00007517 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7519 match(Op0BO->getOperand(0),
7520 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007521 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007522 cast<BinaryOperator>(Op0BO->getOperand(0))
7523 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007524 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007525 Op0BO->getOperand(1), Op1,
7526 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007527 InsertNewInstBefore(YS, I); // (Y << C)
7528 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007529 BinaryOperator::CreateAnd(V1,
7530 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007531 V1->getName()+".mask");
7532 InsertNewInstBefore(XM, I); // X & (CC << C)
7533
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007536
Chris Lattner11021cb2005-09-18 05:12:10 +00007537 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007538 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007539 }
7540
7541
7542 // If the operand is an bitwise operator with a constant RHS, and the
7543 // shift is the only use, we can pull it out of the shift.
7544 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7545 bool isValid = true; // Valid only for And, Or, Xor
7546 bool highBitSet = false; // Transform if high bit of constant set?
7547
7548 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007549 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007550 case Instruction::Add:
7551 isValid = isLeftShift;
7552 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007553 case Instruction::Or:
7554 case Instruction::Xor:
7555 highBitSet = false;
7556 break;
7557 case Instruction::And:
7558 highBitSet = true;
7559 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007560 }
7561
7562 // If this is a signed shift right, and the high bit is modified
7563 // by the logical operation, do not perform the transformation.
7564 // The highBitSet boolean indicates the value of the high bit of
7565 // the constant which would cause it to be modified for this
7566 // operation.
7567 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007568 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007569 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570
7571 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007572 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007573
7574 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007575 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007576 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007577 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007578
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007579 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007580 NewRHS);
7581 }
7582 }
7583 }
7584 }
7585
Chris Lattnerad0124c2006-01-06 07:52:12 +00007586 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007587 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7588 if (ShiftOp && !ShiftOp->isShift())
7589 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007590
Reid Spencerb83eb642006-10-20 07:07:24 +00007591 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007592 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007593 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7594 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007595 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7596 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7597 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007598
Zhou Sheng4351c642007-04-02 08:20:41 +00007599 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007600
7601 const IntegerType *Ty = cast<IntegerType>(I.getType());
7602
7603 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007604 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007605 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7606 // saturates.
7607 if (AmtSum >= TypeBits) {
7608 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007609 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007610 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7611 }
7612
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007613 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007614 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007615 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7616 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007617 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007618 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007619
Chris Lattnerb87056f2007-02-05 00:57:54 +00007620 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007621 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007622 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7623 I.getOpcode() == Instruction::LShr) {
7624 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007625 if (AmtSum >= TypeBits)
7626 AmtSum = TypeBits-1;
7627
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007629 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 InsertNewInstBefore(Shift, I);
7631
Zhou Shenge9e03f62007-03-28 15:02:20 +00007632 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007633 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007634 }
7635
Chris Lattnerb87056f2007-02-05 00:57:54 +00007636 // Okay, if we get here, one shift must be left, and the other shift must be
7637 // right. See if the amounts are equal.
7638 if (ShiftAmt1 == ShiftAmt2) {
7639 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7640 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007641 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007642 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643 }
7644 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7645 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007646 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007647 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 }
7649 // We can simplify ((X << C) >>s C) into a trunc + sext.
7650 // NOTE: we could do this for any C, but that would make 'unusual' integer
7651 // types. For now, just stick to ones well-supported by the code
7652 // generators.
7653 const Type *SExtType = 0;
7654 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007655 case 1 :
7656 case 8 :
7657 case 16 :
7658 case 32 :
7659 case 64 :
7660 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007661 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007662 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007663 default: break;
7664 }
7665 if (SExtType) {
7666 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7667 InsertNewInstBefore(NewTrunc, I);
7668 return new SExtInst(NewTrunc, Ty);
7669 }
7670 // Otherwise, we can't handle it yet.
7671 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007672 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007673
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007674 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 if (I.getOpcode() == Instruction::Shl) {
7676 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7677 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007678 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007679 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007680 InsertNewInstBefore(Shift, I);
7681
Reid Spencer55702aa2007-03-25 21:11:44 +00007682 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007683 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007684 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007685
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007686 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007687 if (I.getOpcode() == Instruction::LShr) {
7688 assert(ShiftOp->getOpcode() == Instruction::Shl);
7689 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007690 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007691 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007692
Reid Spencerd5e30f02007-03-26 17:18:58 +00007693 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007694 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007695 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007696
7697 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7698 } else {
7699 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007700 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007702 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703 if (I.getOpcode() == Instruction::Shl) {
7704 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705 ShiftOp->getOpcode() == Instruction::AShr);
7706 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007707 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007708 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709 InsertNewInstBefore(Shift, I);
7710
Reid Spencer55702aa2007-03-25 21:11:44 +00007711 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007712 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 }
7714
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007715 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007716 if (I.getOpcode() == Instruction::LShr) {
7717 assert(ShiftOp->getOpcode() == Instruction::Shl);
7718 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007719 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720 InsertNewInstBefore(Shift, I);
7721
Reid Spencer68d27cf2007-03-26 23:45:51 +00007722 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007723 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007724 }
7725
7726 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007727 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007728 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007729 return 0;
7730}
7731
Chris Lattnera1be5662002-05-02 17:06:02 +00007732
Chris Lattnercfd65102005-10-29 04:36:15 +00007733/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7734/// expression. If so, decompose it, returning some value X, such that Val is
7735/// X*Scale+Offset.
7736///
7737static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007738 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007739 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007741 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007742 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007743 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007744 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7745 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7746 if (I->getOpcode() == Instruction::Shl) {
7747 // This is a value scaled by '1 << the shift amt'.
7748 Scale = 1U << RHS->getZExtValue();
7749 Offset = 0;
7750 return I->getOperand(0);
7751 } else if (I->getOpcode() == Instruction::Mul) {
7752 // This value is scaled by 'RHS'.
7753 Scale = RHS->getZExtValue();
7754 Offset = 0;
7755 return I->getOperand(0);
7756 } else if (I->getOpcode() == Instruction::Add) {
7757 // We have X+C. Check to see if we really have (X*C2)+C1,
7758 // where C1 is divisible by C2.
7759 unsigned SubScale;
7760 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007761 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7762 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007763 Offset += RHS->getZExtValue();
7764 Scale = SubScale;
7765 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007766 }
7767 }
7768 }
7769
7770 // Otherwise, we can't look past this.
7771 Scale = 1;
7772 Offset = 0;
7773 return Val;
7774}
7775
7776
Chris Lattnerb3f83972005-10-24 06:03:58 +00007777/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7778/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007779Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007780 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007781 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007782
Chris Lattnerb53c2382005-10-24 06:22:12 +00007783 // Remove any uses of AI that are dead.
7784 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007785
Chris Lattnerb53c2382005-10-24 06:22:12 +00007786 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7787 Instruction *User = cast<Instruction>(*UI++);
7788 if (isInstructionTriviallyDead(User)) {
7789 while (UI != E && *UI == User)
7790 ++UI; // If this instruction uses AI more than once, don't break UI.
7791
Chris Lattnerb53c2382005-10-24 06:22:12 +00007792 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007793 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007794 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007795 }
7796 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007797
7798 // This requires TargetData to get the alloca alignment and size information.
7799 if (!TD) return 0;
7800
Chris Lattnerb3f83972005-10-24 06:03:58 +00007801 // Get the type really allocated and the type casted to.
7802 const Type *AllocElTy = AI.getAllocatedType();
7803 const Type *CastElTy = PTy->getElementType();
7804 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007805
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007806 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7807 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007808 if (CastElTyAlign < AllocElTyAlign) return 0;
7809
Chris Lattner39387a52005-10-24 06:35:18 +00007810 // If the allocation has multiple uses, only promote it if we are strictly
7811 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007812 // same, we open the door to infinite loops of various kinds. (A reference
7813 // from a dbg.declare doesn't count as a use for this purpose.)
7814 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7815 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007816
Duncan Sands777d2302009-05-09 07:06:46 +00007817 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7818 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007819 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007820
Chris Lattner455fcc82005-10-29 03:19:53 +00007821 // See if we can satisfy the modulus by pulling a scale out of the array
7822 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007823 unsigned ArraySizeScale;
7824 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007825 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007826 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7827 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007828
Chris Lattner455fcc82005-10-29 03:19:53 +00007829 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7830 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007831 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7832 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007833
Chris Lattner455fcc82005-10-29 03:19:53 +00007834 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7835 Value *Amt = 0;
7836 if (Scale == 1) {
7837 Amt = NumElements;
7838 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007839 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007840 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007841 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007842 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007843 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007844 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007845 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007846 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007847 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007848 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007849 }
7850
Jeff Cohen86796be2007-04-04 16:58:57 +00007851 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007852 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007853 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007854 Amt = InsertNewInstBefore(Tmp, AI);
7855 }
7856
Chris Lattnerb3f83972005-10-24 06:03:58 +00007857 AllocationInst *New;
7858 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007859 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007860 else
Owen Anderson50dead02009-07-15 23:53:25 +00007861 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007862 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007863 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007864
Dale Johannesena0a66372009-03-05 00:39:02 +00007865 // If the allocation has one real use plus a dbg.declare, just remove the
7866 // declare.
7867 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7868 EraseInstFromFunction(*DI);
7869 }
7870 // If the allocation has multiple real uses, insert a cast and change all
7871 // things that used it to use the new cast. This will also hack on CI, but it
7872 // will die soon.
7873 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007874 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007875 // New is the allocation instruction, pointer typed. AI is the original
7876 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7877 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007878 InsertNewInstBefore(NewCast, AI);
7879 AI.replaceAllUsesWith(NewCast);
7880 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007881 return ReplaceInstUsesWith(CI, New);
7882}
7883
Chris Lattner70074e02006-05-13 02:06:03 +00007884/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007885/// and return it as type Ty without inserting any new casts and without
7886/// changing the computed value. This is used by code that tries to decide
7887/// whether promoting or shrinking integer operations to wider or smaller types
7888/// will allow us to eliminate a truncate or extend.
7889///
7890/// This is a truncation operation if Ty is smaller than V->getType(), or an
7891/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007892///
7893/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7894/// should return true if trunc(V) can be computed by computing V in the smaller
7895/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7896/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7897/// efficiently truncated.
7898///
7899/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7900/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7901/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007902bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007903 unsigned CastOpc,
7904 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007905 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007906 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007907 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007908
7909 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910 if (!I) return false;
7911
Dan Gohman6de29f82009-06-15 22:12:54 +00007912 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007913
Chris Lattner951626b2007-08-02 06:11:14 +00007914 // If this is an extension or truncate, we can often eliminate it.
7915 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7916 // If this is a cast from the destination type, we can trivially eliminate
7917 // it, and this will remove a cast overall.
7918 if (I->getOperand(0)->getType() == Ty) {
7919 // If the first operand is itself a cast, and is eliminable, do not count
7920 // this as an eliminable cast. We would prefer to eliminate those two
7921 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007922 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007923 ++NumCastsRemoved;
7924 return true;
7925 }
7926 }
7927
7928 // We can't extend or shrink something that has multiple uses: doing so would
7929 // require duplicating the instruction in general, which isn't profitable.
7930 if (!I->hasOneUse()) return false;
7931
Evan Chengf35fd542009-01-15 17:01:23 +00007932 unsigned Opc = I->getOpcode();
7933 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007934 case Instruction::Add:
7935 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007936 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007937 case Instruction::And:
7938 case Instruction::Or:
7939 case Instruction::Xor:
7940 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007941 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007942 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007943 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007944 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007945
Eli Friedman070a9812009-07-13 22:46:01 +00007946 case Instruction::UDiv:
7947 case Instruction::URem: {
7948 // UDiv and URem can be truncated if all the truncated bits are zero.
7949 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7950 uint32_t BitWidth = Ty->getScalarSizeInBits();
7951 if (BitWidth < OrigBitWidth) {
7952 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7953 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7954 MaskedValueIsZero(I->getOperand(1), Mask)) {
7955 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7956 NumCastsRemoved) &&
7957 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7958 NumCastsRemoved);
7959 }
7960 }
7961 break;
7962 }
Chris Lattner46b96052006-11-29 07:18:39 +00007963 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007964 // If we are truncating the result of this SHL, and if it's a shift of a
7965 // constant amount, we can always perform a SHL in a smaller type.
7966 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007967 uint32_t BitWidth = Ty->getScalarSizeInBits();
7968 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007969 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007970 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007972 }
7973 break;
7974 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007975 // If this is a truncate of a logical shr, we can truncate it to a smaller
7976 // lshr iff we know that the bits we would otherwise be shifting in are
7977 // already zeros.
7978 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007979 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7980 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007981 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007983 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7984 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007985 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007986 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007987 }
7988 }
Chris Lattner46b96052006-11-29 07:18:39 +00007989 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 case Instruction::ZExt:
7991 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007992 case Instruction::Trunc:
7993 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007994 // can safely replace it. Note that replacing it does not reduce the number
7995 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007996 if (Opc == CastOpc)
7997 return true;
7998
7999 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008000 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008001 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008003 case Instruction::Select: {
8004 SelectInst *SI = cast<SelectInst>(I);
8005 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008006 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008007 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008008 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008009 }
Chris Lattner8114b712008-06-18 04:00:49 +00008010 case Instruction::PHI: {
8011 // We can change a phi if we can change all operands.
8012 PHINode *PN = cast<PHINode>(I);
8013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8014 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008015 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008016 return false;
8017 return true;
8018 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008019 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008020 // TODO: Can handle more cases here.
8021 break;
8022 }
8023
8024 return false;
8025}
8026
8027/// EvaluateInDifferentType - Given an expression that
8028/// CanEvaluateInDifferentType returns true for, actually insert the code to
8029/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008030Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008031 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008032 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008033 return Context->getConstantExprIntegerCast(C, Ty,
8034 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008035
8036 // Otherwise, it must be an instruction.
8037 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008038 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008039 unsigned Opc = I->getOpcode();
8040 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008041 case Instruction::Add:
8042 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008043 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008044 case Instruction::And:
8045 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008046 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008047 case Instruction::AShr:
8048 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008049 case Instruction::Shl:
8050 case Instruction::UDiv:
8051 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008052 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008053 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008054 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008055 break;
8056 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 case Instruction::Trunc:
8058 case Instruction::ZExt:
8059 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008060 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008061 // just return the source. There's no need to insert it because it is not
8062 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008063 if (I->getOperand(0)->getType() == Ty)
8064 return I->getOperand(0);
8065
Chris Lattner8114b712008-06-18 04:00:49 +00008066 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008067 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008068 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008069 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008070 case Instruction::Select: {
8071 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8072 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8073 Res = SelectInst::Create(I->getOperand(0), True, False);
8074 break;
8075 }
Chris Lattner8114b712008-06-18 04:00:49 +00008076 case Instruction::PHI: {
8077 PHINode *OPN = cast<PHINode>(I);
8078 PHINode *NPN = PHINode::Create(Ty);
8079 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8080 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8081 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8082 }
8083 Res = NPN;
8084 break;
8085 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008086 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008087 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008088 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008089 break;
8090 }
8091
Chris Lattner8114b712008-06-18 04:00:49 +00008092 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008093 return InsertNewInstBefore(Res, *I);
8094}
8095
Reid Spencer3da59db2006-11-27 01:05:10 +00008096/// @brief Implement the transforms common to all CastInst visitors.
8097Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008098 Value *Src = CI.getOperand(0);
8099
Dan Gohman23d9d272007-05-11 21:10:54 +00008100 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008101 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008102 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 if (Instruction::CastOps opc =
8104 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8105 // The first cast (CSrc) is eliminable so we need to fix up or replace
8106 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008107 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008108 }
8109 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008110
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008112 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8113 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8114 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008115
8116 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008117 if (isa<PHINode>(Src))
8118 if (Instruction *NV = FoldOpIntoPhi(CI))
8119 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008120
Reid Spencer3da59db2006-11-27 01:05:10 +00008121 return 0;
8122}
8123
Chris Lattner46cd5a12009-01-09 05:44:56 +00008124/// FindElementAtOffset - Given a type and a constant offset, determine whether
8125/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008126/// the specified offset. If so, fill them into NewIndices and return the
8127/// resultant element type, otherwise return null.
8128static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8129 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008130 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008131 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008132 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008133 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008134
8135 // Start with the index over the outer type. Note that the type size
8136 // might be zero (even if the offset isn't zero) if the indexed type
8137 // is something like [0 x {int, int}]
8138 const Type *IntPtrTy = TD->getIntPtrType();
8139 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008140 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008141 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008142 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008143
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008144 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008145 if (Offset < 0) {
8146 --FirstIdx;
8147 Offset += TySize;
8148 assert(Offset >= 0);
8149 }
8150 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8151 }
8152
Owen Andersond672ecb2009-07-03 00:17:18 +00008153 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008154
8155 // Index into the types. If we fail, set OrigBase to null.
8156 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008157 // Indexing into tail padding between struct/array elements.
8158 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008159 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008160
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8162 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008163 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8164 "Offset must stay within the indexed type");
8165
Chris Lattner46cd5a12009-01-09 05:44:56 +00008166 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008167 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008168
8169 Offset -= SL->getElementOffset(Elt);
8170 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008171 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008172 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008173 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008174 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008175 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008176 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008178 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008179 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008180 }
8181 }
8182
Chris Lattner3914f722009-01-24 01:00:13 +00008183 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008184}
8185
Chris Lattnerd3e28342007-04-27 17:44:50 +00008186/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8187Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8188 Value *Src = CI.getOperand(0);
8189
Chris Lattnerd3e28342007-04-27 17:44:50 +00008190 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008191 // If casting the result of a getelementptr instruction with no offset, turn
8192 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008193 if (GEP->hasAllZeroIndices()) {
8194 // Changing the cast operand is usually not a good idea but it is safe
8195 // here because the pointer operand is being replaced with another
8196 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008197 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008198 CI.setOperand(0, GEP->getOperand(0));
8199 return &CI;
8200 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008201
8202 // If the GEP has a single use, and the base pointer is a bitcast, and the
8203 // GEP computes a constant offset, see if we can convert these three
8204 // instructions into fewer. This typically happens with unions and other
8205 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008206 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008207 if (GEP->hasAllConstantIndices()) {
8208 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008209 ConstantInt *OffsetV =
8210 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008211 int64_t Offset = OffsetV->getSExtValue();
8212
8213 // Get the base pointer input of the bitcast, and the type it points to.
8214 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8215 const Type *GEPIdxTy =
8216 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008217 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008218 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008219 // If we were able to index down into an element, create the GEP
8220 // and bitcast the result. This eliminates one bitcast, potentially
8221 // two.
8222 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8223 NewIndices.begin(),
8224 NewIndices.end(), "");
8225 InsertNewInstBefore(NGEP, CI);
8226 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008227
Chris Lattner46cd5a12009-01-09 05:44:56 +00008228 if (isa<BitCastInst>(CI))
8229 return new BitCastInst(NGEP, CI.getType());
8230 assert(isa<PtrToIntInst>(CI));
8231 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008232 }
8233 }
8234 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008235 }
8236
8237 return commonCastTransforms(CI);
8238}
8239
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008240/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8241/// type like i42. We don't want to introduce operations on random non-legal
8242/// integer types where they don't already exist in the code. In the future,
8243/// we should consider making this based off target-data, so that 32-bit targets
8244/// won't get i64 operations etc.
8245static bool isSafeIntegerType(const Type *Ty) {
8246 switch (Ty->getPrimitiveSizeInBits()) {
8247 case 8:
8248 case 16:
8249 case 32:
8250 case 64:
8251 return true;
8252 default:
8253 return false;
8254 }
8255}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008256
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008257/// commonIntCastTransforms - This function implements the common transforms
8258/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008259Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8260 if (Instruction *Result = commonCastTransforms(CI))
8261 return Result;
8262
8263 Value *Src = CI.getOperand(0);
8264 const Type *SrcTy = Src->getType();
8265 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008266 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8267 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008268
Reid Spencer3da59db2006-11-27 01:05:10 +00008269 // See if we can simplify any instructions used by the LHS whose sole
8270 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008271 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 return &CI;
8273
8274 // If the source isn't an instruction or has more than one use then we
8275 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008276 Instruction *SrcI = dyn_cast<Instruction>(Src);
8277 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 return 0;
8279
Chris Lattnerc739cd62007-03-03 05:27:34 +00008280 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008282 // Only do this if the dest type is a simple type, don't convert the
8283 // expression tree to something weird like i93 unless the source is also
8284 // strange.
8285 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008286 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8287 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008288 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008290 // eliminates the cast, so it is always a win. If this is a zero-extension,
8291 // we need to do an AND to maintain the clear top-part of the computation,
8292 // so we require that the input have eliminated at least one cast. If this
8293 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008294 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008295 bool DoXForm = false;
8296 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008297 switch (CI.getOpcode()) {
8298 default:
8299 // All the others use floating point so we shouldn't actually
8300 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008301 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008302 case Instruction::Trunc:
8303 DoXForm = true;
8304 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008305 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008306 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008307 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008308 // If it's unnecessary to issue an AND to clear the high bits, it's
8309 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008310 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8312 if (MaskedValueIsZero(TryRes, Mask))
8313 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008314
8315 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008316 if (TryI->use_empty())
8317 EraseInstFromFunction(*TryI);
8318 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008319 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008320 }
Evan Chengf35fd542009-01-15 17:01:23 +00008321 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008322 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008323 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008324 // If we do not have to emit the truncate + sext pair, then it's always
8325 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008326 //
8327 // It's not safe to eliminate the trunc + sext pair if one of the
8328 // eliminated cast is a truncate. e.g.
8329 // t2 = trunc i32 t1 to i16
8330 // t3 = sext i16 t2 to i32
8331 // !=
8332 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008333 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008334 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8335 if (NumSignBits > (DestBitSize - SrcBitSize))
8336 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008337
8338 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008339 if (TryI->use_empty())
8340 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008341 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008342 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008343 }
Evan Chengf35fd542009-01-15 17:01:23 +00008344 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008345
8346 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008347 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8348 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008349 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8350 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008351 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008352 // Just replace this cast with the result.
8353 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354
Reid Spencer3da59db2006-11-27 01:05:10 +00008355 assert(Res->getType() == DestTy);
8356 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008357 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008358 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008359 // Just replace this cast with the result.
8360 return ReplaceInstUsesWith(CI, Res);
8361 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008362 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008363
8364 // If the high bits are already zero, just replace this cast with the
8365 // result.
8366 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8367 if (MaskedValueIsZero(Res, Mask))
8368 return ReplaceInstUsesWith(CI, Res);
8369
8370 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008371 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008372 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008373 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008375 case Instruction::SExt: {
8376 // If the high bits are already filled with sign bit, just replace this
8377 // cast with the result.
8378 unsigned NumSignBits = ComputeNumSignBits(Res);
8379 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008380 return ReplaceInstUsesWith(CI, Res);
8381
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008383 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008384 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8385 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008387 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008388 }
8389 }
8390
8391 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8392 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8393
8394 switch (SrcI->getOpcode()) {
8395 case Instruction::Add:
8396 case Instruction::Mul:
8397 case Instruction::And:
8398 case Instruction::Or:
8399 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008400 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008401 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8402 // Don't insert two casts unless at least one can be eliminated.
8403 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008404 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008405 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8406 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008407 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008408 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 }
8410 }
8411
8412 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8413 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8414 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008415 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008416 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008417 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008418 return BinaryOperator::CreateXor(New,
8419 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008420 }
8421 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008422
Eli Friedman65445c52009-07-13 21:45:57 +00008423 case Instruction::Shl: {
8424 // Canonicalize trunc inside shl, if we can.
8425 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8426 if (CI && DestBitSize < SrcBitSize &&
8427 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8428 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008430 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 }
8432 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008433 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008434 }
8435 return 0;
8436}
8437
Chris Lattner8a9f5712007-04-11 06:57:46 +00008438Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008439 if (Instruction *Result = commonIntCastTransforms(CI))
8440 return Result;
8441
8442 Value *Src = CI.getOperand(0);
8443 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008444 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8445 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008446
8447 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008448 if (DestBitWidth == 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008449 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008450 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008451 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008452 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008453 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008454
Chris Lattner4f9797d2009-03-24 18:15:30 +00008455 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8456 ConstantInt *ShAmtV = 0;
8457 Value *ShiftOp = 0;
8458 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008459 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008460 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8461
8462 // Get a mask for the bits shifting in.
8463 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8464 if (MaskedValueIsZero(ShiftOp, Mask)) {
8465 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008466 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008467
8468 // Okay, we can shrink this. Truncate the input, then return a new
8469 // shift.
8470 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008471 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008472 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008473 }
8474 }
8475
8476 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008477}
8478
Evan Chengb98a10e2008-03-24 00:21:34 +00008479/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8480/// in order to eliminate the icmp.
8481Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8482 bool DoXform) {
8483 // If we are just checking for a icmp eq of a single bit and zext'ing it
8484 // to an integer, then shift the bit to the appropriate place and then
8485 // cast to integer to avoid the comparison.
8486 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8487 const APInt &Op1CV = Op1C->getValue();
8488
8489 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8490 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8491 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8492 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8493 if (!DoXform) return ICI;
8494
8495 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008496 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008497 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008498 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008499 In->getName()+".lobit"),
8500 CI);
8501 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008502 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008503 false/*ZExt*/, "tmp", &CI);
8504
8505 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008506 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008507 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008508 In->getName()+".not"),
8509 CI);
8510 }
8511
8512 return ReplaceInstUsesWith(CI, In);
8513 }
8514
8515
8516
8517 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8518 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8520 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8521 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8522 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8523 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8524 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8525 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8526 // This only works for EQ and NE
8527 ICI->isEquality()) {
8528 // If Op1C some other power of two, convert:
8529 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8530 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8531 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8532 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8533
8534 APInt KnownZeroMask(~KnownZero);
8535 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8536 if (!DoXform) return ICI;
8537
8538 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8539 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8540 // (X&4) == 2 --> false
8541 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008542 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8543 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008544 return ReplaceInstUsesWith(CI, Res);
8545 }
8546
8547 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8548 Value *In = ICI->getOperand(0);
8549 if (ShiftAmt) {
8550 // Perform a logical shr by shiftamt.
8551 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008552 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008553 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008554 In->getName()+".lobit"), CI);
8555 }
8556
8557 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008558 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008559 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008560 InsertNewInstBefore(cast<Instruction>(In), CI);
8561 }
8562
8563 if (CI.getType() == In->getType())
8564 return ReplaceInstUsesWith(CI, In);
8565 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008566 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008567 }
8568 }
8569 }
8570
8571 return 0;
8572}
8573
Chris Lattner8a9f5712007-04-11 06:57:46 +00008574Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008575 // If one of the common conversion will work ..
8576 if (Instruction *Result = commonIntCastTransforms(CI))
8577 return Result;
8578
8579 Value *Src = CI.getOperand(0);
8580
Chris Lattnera84f47c2009-02-17 20:47:23 +00008581 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8582 // types and if the sizes are just right we can convert this into a logical
8583 // 'and' which will be much cheaper than the pair of casts.
8584 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8585 // Get the sizes of the types involved. We know that the intermediate type
8586 // will be smaller than A or C, but don't know the relation between A and C.
8587 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008588 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8589 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8590 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008591 // If we're actually extending zero bits, then if
8592 // SrcSize < DstSize: zext(a & mask)
8593 // SrcSize == DstSize: a & mask
8594 // SrcSize > DstSize: trunc(a) & mask
8595 if (SrcSize < DstSize) {
8596 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008597 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008598 Instruction *And =
8599 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8600 InsertNewInstBefore(And, CI);
8601 return new ZExtInst(And, CI.getType());
8602 } else if (SrcSize == DstSize) {
8603 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008604 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008605 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008606 } else if (SrcSize > DstSize) {
8607 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8608 InsertNewInstBefore(Trunc, CI);
8609 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008610 return BinaryOperator::CreateAnd(Trunc,
8611 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008612 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008613 }
8614 }
8615
Evan Chengb98a10e2008-03-24 00:21:34 +00008616 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8617 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008618
Evan Chengb98a10e2008-03-24 00:21:34 +00008619 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8620 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8621 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8622 // of the (zext icmp) will be transformed.
8623 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8624 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8625 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8626 (transformZExtICmp(LHS, CI, false) ||
8627 transformZExtICmp(RHS, CI, false))) {
8628 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8629 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008630 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008631 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008632 }
8633
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008634 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008635 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8636 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8637 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8638 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008639 if (TI0->getType() == CI.getType())
8640 return
8641 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008642 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008643 }
8644
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008645 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8646 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8647 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8648 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8649 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8650 And->getOperand(1) == C)
8651 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8652 Value *TI0 = TI->getOperand(0);
8653 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008654 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008655 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8656 InsertNewInstBefore(NewAnd, *And);
8657 return BinaryOperator::CreateXor(NewAnd, ZC);
8658 }
8659 }
8660
Reid Spencer3da59db2006-11-27 01:05:10 +00008661 return 0;
8662}
8663
Chris Lattner8a9f5712007-04-11 06:57:46 +00008664Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008665 if (Instruction *I = commonIntCastTransforms(CI))
8666 return I;
8667
Chris Lattner8a9f5712007-04-11 06:57:46 +00008668 Value *Src = CI.getOperand(0);
8669
Dan Gohman1975d032008-10-30 20:40:10 +00008670 // Canonicalize sign-extend from i1 to a select.
8671 if (Src->getType() == Type::Int1Ty)
8672 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008673 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008674 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008675
8676 // See if the value being truncated is already sign extended. If so, just
8677 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008678 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008679 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008680 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8681 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8682 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008683 unsigned NumSignBits = ComputeNumSignBits(Op);
8684
8685 if (OpBits == DestBits) {
8686 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8687 // bits, it is already ready.
8688 if (NumSignBits > DestBits-MidBits)
8689 return ReplaceInstUsesWith(CI, Op);
8690 } else if (OpBits < DestBits) {
8691 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8692 // bits, just sext from i32.
8693 if (NumSignBits > OpBits-MidBits)
8694 return new SExtInst(Op, CI.getType(), "tmp");
8695 } else {
8696 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8697 // bits, just truncate to i32.
8698 if (NumSignBits > OpBits-MidBits)
8699 return new TruncInst(Op, CI.getType(), "tmp");
8700 }
8701 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008702
8703 // If the input is a shl/ashr pair of a same constant, then this is a sign
8704 // extension from a smaller value. If we could trust arbitrary bitwidth
8705 // integers, we could turn this into a truncate to the smaller bit and then
8706 // use a sext for the whole extension. Since we don't, look deeper and check
8707 // for a truncate. If the source and dest are the same type, eliminate the
8708 // trunc and extend and just do shifts. For example, turn:
8709 // %a = trunc i32 %i to i8
8710 // %b = shl i8 %a, 6
8711 // %c = ashr i8 %b, 6
8712 // %d = sext i8 %c to i32
8713 // into:
8714 // %a = shl i32 %i, 30
8715 // %d = ashr i32 %a, 30
8716 Value *A = 0;
8717 ConstantInt *BA = 0, *CA = 0;
8718 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008719 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008720 BA == CA && isa<TruncInst>(A)) {
8721 Value *I = cast<TruncInst>(A)->getOperand(0);
8722 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008723 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8724 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008725 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008726 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008727 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8728 CI.getName()), CI);
8729 return BinaryOperator::CreateAShr(I, ShAmtV);
8730 }
8731 }
8732
Chris Lattnerba417832007-04-11 06:12:58 +00008733 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008734}
8735
Chris Lattnerb7530652008-01-27 05:29:54 +00008736/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8737/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008738static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008739 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008740 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008741 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008742 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8743 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008744 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008745 return 0;
8746}
8747
8748/// LookThroughFPExtensions - If this is an fp extension instruction, look
8749/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008750static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008751 if (Instruction *I = dyn_cast<Instruction>(V))
8752 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008753 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008754
8755 // If this value is a constant, return the constant in the smallest FP type
8756 // that can accurately represent it. This allows us to turn
8757 // (float)((double)X+2.0) into x+2.0f.
8758 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8759 if (CFP->getType() == Type::PPC_FP128Ty)
8760 return V; // No constant folding of this.
8761 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008762 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008763 return V;
8764 if (CFP->getType() == Type::DoubleTy)
8765 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008766 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008767 return V;
8768 // Don't try to shrink to various long double types.
8769 }
8770
8771 return V;
8772}
8773
8774Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8775 if (Instruction *I = commonCastTransforms(CI))
8776 return I;
8777
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008778 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008779 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008780 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008781 // many builtins (sqrt, etc).
8782 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8783 if (OpI && OpI->hasOneUse()) {
8784 switch (OpI->getOpcode()) {
8785 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008786 case Instruction::FAdd:
8787 case Instruction::FSub:
8788 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 case Instruction::FDiv:
8790 case Instruction::FRem:
8791 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008792 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8793 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008794 if (LHSTrunc->getType() != SrcTy &&
8795 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008796 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008797 // If the source types were both smaller than the destination type of
8798 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008799 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8800 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8802 CI.getType(), CI);
8803 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8804 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008805 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008806 }
8807 }
8808 break;
8809 }
8810 }
8811 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008812}
8813
8814Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8815 return commonCastTransforms(CI);
8816}
8817
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008818Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008819 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8820 if (OpI == 0)
8821 return commonCastTransforms(FI);
8822
8823 // fptoui(uitofp(X)) --> X
8824 // fptoui(sitofp(X)) --> X
8825 // This is safe if the intermediate type has enough bits in its mantissa to
8826 // accurately represent all values of X. For example, do not do this with
8827 // i64->float->i64. This is also safe for sitofp case, because any negative
8828 // 'X' value would cause an undefined result for the fptoui.
8829 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8830 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008831 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008832 OpI->getType()->getFPMantissaWidth())
8833 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008834
8835 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008836}
8837
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008838Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008839 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8840 if (OpI == 0)
8841 return commonCastTransforms(FI);
8842
8843 // fptosi(sitofp(X)) --> X
8844 // fptosi(uitofp(X)) --> X
8845 // This is safe if the intermediate type has enough bits in its mantissa to
8846 // accurately represent all values of X. For example, do not do this with
8847 // i64->float->i64. This is also safe for sitofp case, because any negative
8848 // 'X' value would cause an undefined result for the fptoui.
8849 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8850 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008851 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008852 OpI->getType()->getFPMantissaWidth())
8853 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008854
8855 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008856}
8857
8858Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8859 return commonCastTransforms(CI);
8860}
8861
8862Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8863 return commonCastTransforms(CI);
8864}
8865
Chris Lattnera0e69692009-03-24 18:35:40 +00008866Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8867 // If the destination integer type is smaller than the intptr_t type for
8868 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8869 // trunc to be exposed to other transforms. Don't do this for extending
8870 // ptrtoint's, because we don't know if the target sign or zero extends its
8871 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008872 if (TD &&
8873 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008874 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8875 TD->getIntPtrType(),
8876 "tmp"), CI);
8877 return new TruncInst(P, CI.getType());
8878 }
8879
Chris Lattnerd3e28342007-04-27 17:44:50 +00008880 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008881}
8882
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008883Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008884 // If the source integer type is larger than the intptr_t type for
8885 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8886 // allows the trunc to be exposed to other transforms. Don't do this for
8887 // extending inttoptr's, because we don't know if the target sign or zero
8888 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008889 if (TD &&
8890 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008891 TD->getPointerSizeInBits()) {
8892 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8893 TD->getIntPtrType(),
8894 "tmp"), CI);
8895 return new IntToPtrInst(P, CI.getType());
8896 }
8897
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008898 if (Instruction *I = commonCastTransforms(CI))
8899 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008900
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008901 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008902}
8903
Chris Lattnerd3e28342007-04-27 17:44:50 +00008904Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008905 // If the operands are integer typed then apply the integer transforms,
8906 // otherwise just apply the common ones.
8907 Value *Src = CI.getOperand(0);
8908 const Type *SrcTy = Src->getType();
8909 const Type *DestTy = CI.getType();
8910
Eli Friedman7e25d452009-07-13 20:53:00 +00008911 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008912 if (Instruction *I = commonPointerCastTransforms(CI))
8913 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008914 } else {
8915 if (Instruction *Result = commonCastTransforms(CI))
8916 return Result;
8917 }
8918
8919
8920 // Get rid of casts from one type to the same type. These are useless and can
8921 // be replaced by the operand.
8922 if (DestTy == Src->getType())
8923 return ReplaceInstUsesWith(CI, Src);
8924
Reid Spencer3da59db2006-11-27 01:05:10 +00008925 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008926 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8927 const Type *DstElTy = DstPTy->getElementType();
8928 const Type *SrcElTy = SrcPTy->getElementType();
8929
Nate Begeman83ad90a2008-03-31 00:22:16 +00008930 // If the address spaces don't match, don't eliminate the bitcast, which is
8931 // required for changing types.
8932 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8933 return 0;
8934
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935 // If we are casting a malloc or alloca to a pointer to a type of the same
8936 // size, rewrite the allocation instruction to allocate the "right" type.
8937 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8938 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8939 return V;
8940
Chris Lattnerd717c182007-05-05 22:32:24 +00008941 // If the source and destination are pointers, and this cast is equivalent
8942 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008943 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008944 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008945 unsigned NumZeros = 0;
8946 while (SrcElTy != DstElTy &&
8947 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8948 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8949 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8950 ++NumZeros;
8951 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008952
Chris Lattnerd3e28342007-04-27 17:44:50 +00008953 // If we found a path from the src to dest, create the getelementptr now.
8954 if (SrcElTy == DstElTy) {
8955 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008956 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8957 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008958 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008959 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008960
Eli Friedman2451a642009-07-18 23:06:53 +00008961 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8962 if (DestVTy->getNumElements() == 1) {
8963 if (!isa<VectorType>(SrcTy)) {
8964 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8965 DestVTy->getElementType(), CI);
8966 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8967 Context->getNullValue(Type::Int32Ty));
8968 }
8969 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8970 }
8971 }
8972
8973 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8974 if (SrcVTy->getNumElements() == 1) {
8975 if (!isa<VectorType>(DestTy)) {
8976 Instruction *Elem =
8977 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8978 InsertNewInstBefore(Elem, CI);
8979 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8980 }
8981 }
8982 }
8983
Reid Spencer3da59db2006-11-27 01:05:10 +00008984 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8985 if (SVI->hasOneUse()) {
8986 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8987 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008988 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008989 cast<VectorType>(DestTy)->getNumElements() ==
8990 SVI->getType()->getNumElements() &&
8991 SVI->getType()->getNumElements() ==
8992 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008993 CastInst *Tmp;
8994 // If either of the operands is a cast from CI.getType(), then
8995 // evaluating the shuffle in the casted destination's type will allow
8996 // us to eliminate at least one cast.
8997 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8998 Tmp->getOperand(0)->getType() == DestTy) ||
8999 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9000 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009001 Value *LHS = InsertCastBefore(Instruction::BitCast,
9002 SVI->getOperand(0), DestTy, CI);
9003 Value *RHS = InsertCastBefore(Instruction::BitCast,
9004 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009005 // Return a new shuffle vector. Use the same element ID's, as we
9006 // know the vector types match #elts.
9007 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009008 }
9009 }
9010 }
9011 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009012 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009013}
9014
Chris Lattnere576b912004-04-09 23:46:01 +00009015/// GetSelectFoldableOperands - We want to turn code that looks like this:
9016/// %C = or %A, %B
9017/// %D = select %cond, %C, %A
9018/// into:
9019/// %C = select %cond, %B, 0
9020/// %D = or %A, %C
9021///
9022/// Assuming that the specified instruction is an operand to the select, return
9023/// a bitmask indicating which operands of this instruction are foldable if they
9024/// equal the other incoming value of the select.
9025///
9026static unsigned GetSelectFoldableOperands(Instruction *I) {
9027 switch (I->getOpcode()) {
9028 case Instruction::Add:
9029 case Instruction::Mul:
9030 case Instruction::And:
9031 case Instruction::Or:
9032 case Instruction::Xor:
9033 return 3; // Can fold through either operand.
9034 case Instruction::Sub: // Can only fold on the amount subtracted.
9035 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009036 case Instruction::LShr:
9037 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009038 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009039 default:
9040 return 0; // Cannot fold
9041 }
9042}
9043
9044/// GetSelectFoldableConstant - For the same transformation as the previous
9045/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009046static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009047 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009048 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009049 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009050 case Instruction::Add:
9051 case Instruction::Sub:
9052 case Instruction::Or:
9053 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009054 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009055 case Instruction::LShr:
9056 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009057 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009058 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009059 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009060 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009061 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009062 }
9063}
9064
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009065/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9066/// have the same opcode and only one use each. Try to simplify this.
9067Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9068 Instruction *FI) {
9069 if (TI->getNumOperands() == 1) {
9070 // If this is a non-volatile load or a cast from the same type,
9071 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009072 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009073 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9074 return 0;
9075 } else {
9076 return 0; // unknown unary op.
9077 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009078
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009079 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009080 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9081 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009082 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009083 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009084 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009085 }
9086
Reid Spencer832254e2007-02-02 02:16:23 +00009087 // Only handle binary operators here.
9088 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009089 return 0;
9090
9091 // Figure out if the operations have any operands in common.
9092 Value *MatchOp, *OtherOpT, *OtherOpF;
9093 bool MatchIsOpZero;
9094 if (TI->getOperand(0) == FI->getOperand(0)) {
9095 MatchOp = TI->getOperand(0);
9096 OtherOpT = TI->getOperand(1);
9097 OtherOpF = FI->getOperand(1);
9098 MatchIsOpZero = true;
9099 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9100 MatchOp = TI->getOperand(1);
9101 OtherOpT = TI->getOperand(0);
9102 OtherOpF = FI->getOperand(0);
9103 MatchIsOpZero = false;
9104 } else if (!TI->isCommutative()) {
9105 return 0;
9106 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9107 MatchOp = TI->getOperand(0);
9108 OtherOpT = TI->getOperand(1);
9109 OtherOpF = FI->getOperand(0);
9110 MatchIsOpZero = true;
9111 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9112 MatchOp = TI->getOperand(1);
9113 OtherOpT = TI->getOperand(0);
9114 OtherOpF = FI->getOperand(1);
9115 MatchIsOpZero = true;
9116 } else {
9117 return 0;
9118 }
9119
9120 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009121 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9122 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 InsertNewInstBefore(NewSI, SI);
9124
9125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9126 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009127 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009128 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009129 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009130 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009131 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009132 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009133}
9134
Evan Chengde621922009-03-31 20:42:45 +00009135static bool isSelect01(Constant *C1, Constant *C2) {
9136 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9137 if (!C1I)
9138 return false;
9139 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9140 if (!C2I)
9141 return false;
9142 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9143}
9144
9145/// FoldSelectIntoOp - Try fold the select into one of the operands to
9146/// facilitate further optimization.
9147Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9148 Value *FalseVal) {
9149 // See the comment above GetSelectFoldableOperands for a description of the
9150 // transformation we are doing here.
9151 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9152 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9153 !isa<Constant>(FalseVal)) {
9154 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9155 unsigned OpToFold = 0;
9156 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9157 OpToFold = 1;
9158 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9159 OpToFold = 2;
9160 }
9161
9162 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009163 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009164 Value *OOp = TVI->getOperand(2-OpToFold);
9165 // Avoid creating select between 2 constants unless it's selecting
9166 // between 0 and 1.
9167 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9168 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9169 InsertNewInstBefore(NewSel, SI);
9170 NewSel->takeName(TVI);
9171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9172 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009173 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009174 }
9175 }
9176 }
9177 }
9178 }
9179
9180 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9181 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9182 !isa<Constant>(TrueVal)) {
9183 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9184 unsigned OpToFold = 0;
9185 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9186 OpToFold = 1;
9187 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9188 OpToFold = 2;
9189 }
9190
9191 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009192 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009193 Value *OOp = FVI->getOperand(2-OpToFold);
9194 // Avoid creating select between 2 constants unless it's selecting
9195 // between 0 and 1.
9196 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9197 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9198 InsertNewInstBefore(NewSel, SI);
9199 NewSel->takeName(FVI);
9200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9201 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009202 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009203 }
9204 }
9205 }
9206 }
9207 }
9208
9209 return 0;
9210}
9211
Dan Gohman81b28ce2008-09-16 18:46:06 +00009212/// visitSelectInstWithICmp - Visit a SelectInst that has an
9213/// ICmpInst as its first operand.
9214///
9215Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9216 ICmpInst *ICI) {
9217 bool Changed = false;
9218 ICmpInst::Predicate Pred = ICI->getPredicate();
9219 Value *CmpLHS = ICI->getOperand(0);
9220 Value *CmpRHS = ICI->getOperand(1);
9221 Value *TrueVal = SI.getTrueValue();
9222 Value *FalseVal = SI.getFalseValue();
9223
9224 // Check cases where the comparison is with a constant that
9225 // can be adjusted to fit the min/max idiom. We may edit ICI in
9226 // place here, so make sure the select is the only user.
9227 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009228 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009229 switch (Pred) {
9230 default: break;
9231 case ICmpInst::ICMP_ULT:
9232 case ICmpInst::ICMP_SLT: {
9233 // X < MIN ? T : F --> F
9234 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9235 return ReplaceInstUsesWith(SI, FalseVal);
9236 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009237 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009238 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9239 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9240 Pred = ICmpInst::getSwappedPredicate(Pred);
9241 CmpRHS = AdjustedRHS;
9242 std::swap(FalseVal, TrueVal);
9243 ICI->setPredicate(Pred);
9244 ICI->setOperand(1, CmpRHS);
9245 SI.setOperand(1, TrueVal);
9246 SI.setOperand(2, FalseVal);
9247 Changed = true;
9248 }
9249 break;
9250 }
9251 case ICmpInst::ICMP_UGT:
9252 case ICmpInst::ICMP_SGT: {
9253 // X > MAX ? T : F --> F
9254 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9255 return ReplaceInstUsesWith(SI, FalseVal);
9256 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009257 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009258 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9259 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9260 Pred = ICmpInst::getSwappedPredicate(Pred);
9261 CmpRHS = AdjustedRHS;
9262 std::swap(FalseVal, TrueVal);
9263 ICI->setPredicate(Pred);
9264 ICI->setOperand(1, CmpRHS);
9265 SI.setOperand(1, TrueVal);
9266 SI.setOperand(2, FalseVal);
9267 Changed = true;
9268 }
9269 break;
9270 }
9271 }
9272
Dan Gohman1975d032008-10-30 20:40:10 +00009273 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9274 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009275 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009276 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9277 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009278 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009279 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9280 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009281 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9282
Dan Gohman1975d032008-10-30 20:40:10 +00009283 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9284 // If we are just checking for a icmp eq of a single bit and zext'ing it
9285 // to an integer, then shift the bit to the appropriate place and then
9286 // cast to integer to avoid the comparison.
9287 const APInt &Op1CV = CI->getValue();
9288
9289 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9290 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9291 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009292 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009293 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009294 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009295 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009296 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9297 In->getName()+".lobit"),
9298 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009299 if (In->getType() != SI.getType())
9300 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009301 true/*SExt*/, "tmp", ICI);
9302
9303 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009304 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009305 In->getName()+".not"), *ICI);
9306
9307 return ReplaceInstUsesWith(SI, In);
9308 }
9309 }
9310 }
9311
Dan Gohman81b28ce2008-09-16 18:46:06 +00009312 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9313 // Transform (X == Y) ? X : Y -> Y
9314 if (Pred == ICmpInst::ICMP_EQ)
9315 return ReplaceInstUsesWith(SI, FalseVal);
9316 // Transform (X != Y) ? X : Y -> X
9317 if (Pred == ICmpInst::ICMP_NE)
9318 return ReplaceInstUsesWith(SI, TrueVal);
9319 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9320
9321 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9322 // Transform (X == Y) ? Y : X -> X
9323 if (Pred == ICmpInst::ICMP_EQ)
9324 return ReplaceInstUsesWith(SI, FalseVal);
9325 // Transform (X != Y) ? Y : X -> Y
9326 if (Pred == ICmpInst::ICMP_NE)
9327 return ReplaceInstUsesWith(SI, TrueVal);
9328 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9329 }
9330
9331 /// NOTE: if we wanted to, this is where to detect integer ABS
9332
9333 return Changed ? &SI : 0;
9334}
9335
Chris Lattner3d69f462004-03-12 05:52:32 +00009336Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009337 Value *CondVal = SI.getCondition();
9338 Value *TrueVal = SI.getTrueValue();
9339 Value *FalseVal = SI.getFalseValue();
9340
9341 // select true, X, Y -> X
9342 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009343 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009344 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009345
9346 // select C, X, X -> X
9347 if (TrueVal == FalseVal)
9348 return ReplaceInstUsesWith(SI, TrueVal);
9349
Chris Lattnere87597f2004-10-16 18:11:37 +00009350 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9351 return ReplaceInstUsesWith(SI, FalseVal);
9352 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9353 return ReplaceInstUsesWith(SI, TrueVal);
9354 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9355 if (isa<Constant>(TrueVal))
9356 return ReplaceInstUsesWith(SI, TrueVal);
9357 else
9358 return ReplaceInstUsesWith(SI, FalseVal);
9359 }
9360
Reid Spencer4fe16d62007-01-11 18:21:29 +00009361 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009362 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009363 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009364 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009365 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009366 } else {
9367 // Change: A = select B, false, C --> A = and !B, C
9368 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009369 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009370 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009371 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009372 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009373 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009374 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009375 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009376 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009377 } else {
9378 // Change: A = select B, C, true --> A = or !B, C
9379 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009380 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009381 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009382 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009383 }
9384 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009385
9386 // select a, b, a -> a&b
9387 // select a, a, b -> a|b
9388 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009389 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009390 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009391 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009392 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009393
Chris Lattner2eefe512004-04-09 19:05:30 +00009394 // Selecting between two integer constants?
9395 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9396 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009397 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009398 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009399 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009400 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009401 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009402 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009403 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009404 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009405 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009406 }
Chris Lattner457dd822004-06-09 07:59:58 +00009407
Reid Spencere4d87aa2006-12-23 06:05:41 +00009408 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009409 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009410 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009411 // non-constant value, eliminate this whole mess. This corresponds to
9412 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009413 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009414 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009415 cast<Constant>(IC->getOperand(1))->isNullValue())
9416 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9417 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009418 isa<ConstantInt>(ICA->getOperand(1)) &&
9419 (ICA->getOperand(1) == TrueValC ||
9420 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009421 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9422 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009423 // know whether we have a icmp_ne or icmp_eq and whether the
9424 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009425 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009426 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009427 Value *V = ICA;
9428 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009429 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009430 Instruction::Xor, V, ICA->getOperand(1)), SI);
9431 return ReplaceInstUsesWith(SI, V);
9432 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009433 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009434 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009435
9436 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009437 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9438 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009439 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009440 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9441 // This is not safe in general for floating point:
9442 // consider X== -0, Y== +0.
9443 // It becomes safe if either operand is a nonzero constant.
9444 ConstantFP *CFPt, *CFPf;
9445 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9446 !CFPt->getValueAPF().isZero()) ||
9447 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9448 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009449 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009450 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009451 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009452 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009453 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009454 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009455
Reid Spencere4d87aa2006-12-23 06:05:41 +00009456 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009457 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009458 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9459 // This is not safe in general for floating point:
9460 // consider X== -0, Y== +0.
9461 // It becomes safe if either operand is a nonzero constant.
9462 ConstantFP *CFPt, *CFPf;
9463 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9464 !CFPt->getValueAPF().isZero()) ||
9465 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9466 !CFPf->getValueAPF().isZero()))
9467 return ReplaceInstUsesWith(SI, FalseVal);
9468 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009469 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009470 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9471 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009472 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009473 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009474 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 }
9476
9477 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009478 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9479 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9480 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009481
Chris Lattner87875da2005-01-13 22:52:24 +00009482 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9483 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9484 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009485 Instruction *AddOp = 0, *SubOp = 0;
9486
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009487 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9488 if (TI->getOpcode() == FI->getOpcode())
9489 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9490 return IV;
9491
9492 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9493 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009494 if ((TI->getOpcode() == Instruction::Sub &&
9495 FI->getOpcode() == Instruction::Add) ||
9496 (TI->getOpcode() == Instruction::FSub &&
9497 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009498 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009499 } else if ((FI->getOpcode() == Instruction::Sub &&
9500 TI->getOpcode() == Instruction::Add) ||
9501 (FI->getOpcode() == Instruction::FSub &&
9502 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009503 AddOp = TI; SubOp = FI;
9504 }
9505
9506 if (AddOp) {
9507 Value *OtherAddOp = 0;
9508 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9509 OtherAddOp = AddOp->getOperand(1);
9510 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9511 OtherAddOp = AddOp->getOperand(0);
9512 }
9513
9514 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009515 // So at this point we know we have (Y -> OtherAddOp):
9516 // select C, (add X, Y), (sub X, Z)
9517 Value *NegVal; // Compute -Z
9518 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009519 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009520 } else {
9521 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009522 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9523 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009524 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009525
9526 Value *NewTrueOp = OtherAddOp;
9527 Value *NewFalseOp = NegVal;
9528 if (AddOp != TI)
9529 std::swap(NewTrueOp, NewFalseOp);
9530 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009531 SelectInst::Create(CondVal, NewTrueOp,
9532 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009533
9534 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009535 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009536 }
9537 }
9538 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009539
Chris Lattnere576b912004-04-09 23:46:01 +00009540 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009541 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009542 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9543 if (FoldI)
9544 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009545 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009546
9547 if (BinaryOperator::isNot(CondVal)) {
9548 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9549 SI.setOperand(1, FalseVal);
9550 SI.setOperand(2, TrueVal);
9551 return &SI;
9552 }
9553
Chris Lattner3d69f462004-03-12 05:52:32 +00009554 return 0;
9555}
9556
Dan Gohmaneee962e2008-04-10 18:43:06 +00009557/// EnforceKnownAlignment - If the specified pointer points to an object that
9558/// we control, modify the object's alignment to PrefAlign. This isn't
9559/// often possible though. If alignment is important, a more reliable approach
9560/// is to simply align all global variables and allocation instructions to
9561/// their preferred alignment from the beginning.
9562///
9563static unsigned EnforceKnownAlignment(Value *V,
9564 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009565
Dan Gohmaneee962e2008-04-10 18:43:06 +00009566 User *U = dyn_cast<User>(V);
9567 if (!U) return Align;
9568
Dan Gohmanca178902009-07-17 20:47:02 +00009569 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009570 default: break;
9571 case Instruction::BitCast:
9572 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9573 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009574 // If all indexes are zero, it is just the alignment of the base pointer.
9575 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009576 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009577 if (!isa<Constant>(*i) ||
9578 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009579 AllZeroOperands = false;
9580 break;
9581 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009582
9583 if (AllZeroOperands) {
9584 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009585 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009586 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009587 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009588 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009589 }
9590
9591 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9592 // If there is a large requested alignment and we can, bump up the alignment
9593 // of the global.
9594 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009595 if (GV->getAlignment() >= PrefAlign)
9596 Align = GV->getAlignment();
9597 else {
9598 GV->setAlignment(PrefAlign);
9599 Align = PrefAlign;
9600 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009601 }
9602 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9603 // If there is a requested alignment and if this is an alloca, round up. We
9604 // don't do this for malloc, because some systems can't respect the request.
9605 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009606 if (AI->getAlignment() >= PrefAlign)
9607 Align = AI->getAlignment();
9608 else {
9609 AI->setAlignment(PrefAlign);
9610 Align = PrefAlign;
9611 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009612 }
9613 }
9614
9615 return Align;
9616}
9617
9618/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9619/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9620/// and it is more than the alignment of the ultimate object, see if we can
9621/// increase the alignment of the ultimate object, making this check succeed.
9622unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9623 unsigned PrefAlign) {
9624 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9625 sizeof(PrefAlign) * CHAR_BIT;
9626 APInt Mask = APInt::getAllOnesValue(BitWidth);
9627 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9628 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9629 unsigned TrailZ = KnownZero.countTrailingOnes();
9630 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9631
9632 if (PrefAlign > Align)
9633 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9634
9635 // We don't need to make any adjustment.
9636 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009637}
9638
Chris Lattnerf497b022008-01-13 23:50:23 +00009639Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009640 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009641 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009642 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009643 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009644
9645 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009646 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9647 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009648 return MI;
9649 }
9650
9651 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9652 // load/store.
9653 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9654 if (MemOpLength == 0) return 0;
9655
Chris Lattner37ac6082008-01-14 00:28:35 +00009656 // Source and destination pointer types are always "i8*" for intrinsic. See
9657 // if the size is something we can handle with a single primitive load/store.
9658 // A single load+store correctly handles overlapping memory in the memmove
9659 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009660 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009661 if (Size == 0) return MI; // Delete this mem transfer.
9662
9663 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009664 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009665
Chris Lattner37ac6082008-01-14 00:28:35 +00009666 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009667 Type *NewPtrTy =
9668 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009669
9670 // Memcpy forces the use of i8* for the source and destination. That means
9671 // that if you're using memcpy to move one double around, you'll get a cast
9672 // from double* to i8*. We'd much rather use a double load+store rather than
9673 // an i64 load+store, here because this improves the odds that the source or
9674 // dest address will be promotable. See if we can find a better type than the
9675 // integer datatype.
9676 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9677 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009678 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009679 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9680 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009681 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009682 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9683 if (STy->getNumElements() == 1)
9684 SrcETy = STy->getElementType(0);
9685 else
9686 break;
9687 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9688 if (ATy->getNumElements() == 1)
9689 SrcETy = ATy->getElementType();
9690 else
9691 break;
9692 } else
9693 break;
9694 }
9695
Dan Gohman8f8e2692008-05-23 01:52:21 +00009696 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009697 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 }
9699 }
9700
9701
Chris Lattnerf497b022008-01-13 23:50:23 +00009702 // If the memcpy/memmove provides better alignment info than we can
9703 // infer, use it.
9704 SrcAlign = std::max(SrcAlign, CopyAlign);
9705 DstAlign = std::max(DstAlign, CopyAlign);
9706
9707 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9708 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009709 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9710 InsertNewInstBefore(L, *MI);
9711 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9712
9713 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009714 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009715 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009716}
Chris Lattner3d69f462004-03-12 05:52:32 +00009717
Chris Lattner69ea9d22008-04-30 06:39:11 +00009718Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9719 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009720 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009721 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9722 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009723 return MI;
9724 }
9725
9726 // Extract the length and alignment and fill if they are constant.
9727 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9728 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9729 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9730 return 0;
9731 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009732 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009733
9734 // If the length is zero, this is a no-op
9735 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9736
9737 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9738 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009739 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009740
9741 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009742 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009743
9744 // Alignment 0 is identity for alignment 1 for memset, but not store.
9745 if (Alignment == 0) Alignment = 1;
9746
9747 // Extract the fill value and store.
9748 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009749 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9750 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009751
9752 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009753 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009754 return MI;
9755 }
9756
9757 return 0;
9758}
9759
9760
Chris Lattner8b0ea312006-01-13 20:11:04 +00009761/// visitCallInst - CallInst simplification. This mostly only handles folding
9762/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9763/// the heavy lifting.
9764///
Chris Lattner9fe38862003-06-19 17:00:31 +00009765Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009766 // If the caller function is nounwind, mark the call as nounwind, even if the
9767 // callee isn't.
9768 if (CI.getParent()->getParent()->doesNotThrow() &&
9769 !CI.doesNotThrow()) {
9770 CI.setDoesNotThrow();
9771 return &CI;
9772 }
9773
9774
9775
Chris Lattner8b0ea312006-01-13 20:11:04 +00009776 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9777 if (!II) return visitCallSite(&CI);
9778
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009779 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9780 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009781 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009782 bool Changed = false;
9783
9784 // memmove/cpy/set of zero bytes is a noop.
9785 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9786 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9787
Chris Lattner35b9e482004-10-12 04:52:52 +00009788 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009789 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009790 // Replace the instruction with just byte operations. We would
9791 // transform other cases to loads/stores, but we don't know if
9792 // alignment is sufficient.
9793 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009794 }
9795
Chris Lattner35b9e482004-10-12 04:52:52 +00009796 // If we have a memmove and the source operation is a constant global,
9797 // then the source and dest pointers can't alias, so we can change this
9798 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009799 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009800 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9801 if (GVSrc->isConstant()) {
9802 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009803 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9804 const Type *Tys[1];
9805 Tys[0] = CI.getOperand(3)->getType();
9806 CI.setOperand(0,
9807 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009808 Changed = true;
9809 }
Chris Lattnera935db82008-05-28 05:30:41 +00009810
9811 // memmove(x,x,size) -> noop.
9812 if (MMI->getSource() == MMI->getDest())
9813 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009814 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009815
Chris Lattner95a959d2006-03-06 20:18:44 +00009816 // If we can determine a pointer alignment that is bigger than currently
9817 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009818 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009819 if (Instruction *I = SimplifyMemTransfer(MI))
9820 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009821 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9822 if (Instruction *I = SimplifyMemSet(MSI))
9823 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009824 }
9825
Chris Lattner8b0ea312006-01-13 20:11:04 +00009826 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009827 }
9828
9829 switch (II->getIntrinsicID()) {
9830 default: break;
9831 case Intrinsic::bswap:
9832 // bswap(bswap(x)) -> x
9833 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9834 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9835 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9836 break;
9837 case Intrinsic::ppc_altivec_lvx:
9838 case Intrinsic::ppc_altivec_lvxl:
9839 case Intrinsic::x86_sse_loadu_ps:
9840 case Intrinsic::x86_sse2_loadu_pd:
9841 case Intrinsic::x86_sse2_loadu_dq:
9842 // Turn PPC lvx -> load if the pointer is known aligned.
9843 // Turn X86 loadups -> load if the pointer is known aligned.
9844 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9845 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009846 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847 CI);
9848 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009849 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009850 break;
9851 case Intrinsic::ppc_altivec_stvx:
9852 case Intrinsic::ppc_altivec_stvxl:
9853 // Turn stvx -> store if the pointer is known aligned.
9854 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9855 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009856 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009857 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9858 return new StoreInst(II->getOperand(1), Ptr);
9859 }
9860 break;
9861 case Intrinsic::x86_sse_storeu_ps:
9862 case Intrinsic::x86_sse2_storeu_pd:
9863 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 // Turn X86 storeu -> store if the pointer is known aligned.
9865 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9866 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009867 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009868 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9869 return new StoreInst(II->getOperand(2), Ptr);
9870 }
9871 break;
9872
9873 case Intrinsic::x86_sse_cvttss2si: {
9874 // These intrinsics only demands the 0th element of its input vector. If
9875 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009876 unsigned VWidth =
9877 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9878 APInt DemandedElts(VWidth, 1);
9879 APInt UndefElts(VWidth, 0);
9880 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009881 UndefElts)) {
9882 II->setOperand(1, V);
9883 return II;
9884 }
9885 break;
9886 }
9887
9888 case Intrinsic::ppc_altivec_vperm:
9889 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9890 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9891 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009892
Chris Lattner0521e3c2008-06-18 04:33:20 +00009893 // Check that all of the elements are integer constants or undefs.
9894 bool AllEltsOk = true;
9895 for (unsigned i = 0; i != 16; ++i) {
9896 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9897 !isa<UndefValue>(Mask->getOperand(i))) {
9898 AllEltsOk = false;
9899 break;
9900 }
9901 }
9902
9903 if (AllEltsOk) {
9904 // Cast the input vectors to byte vectors.
9905 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9906 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009907 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009908
Chris Lattner0521e3c2008-06-18 04:33:20 +00009909 // Only extract each element once.
9910 Value *ExtractedElts[32];
9911 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9912
Chris Lattnere2ed0572006-04-06 19:19:17 +00009913 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009914 if (isa<UndefValue>(Mask->getOperand(i)))
9915 continue;
9916 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9917 Idx &= 31; // Match the hardware behavior.
9918
9919 if (ExtractedElts[Idx] == 0) {
9920 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009921 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9922 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 InsertNewInstBefore(Elt, CI);
9924 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009925 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009926
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 // Insert this value into the result vector.
9928 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009929 Context->getConstantInt(Type::Int32Ty, i, false),
9930 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009932 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009933 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009934 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009935 }
9936 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009937
Chris Lattner0521e3c2008-06-18 04:33:20 +00009938 case Intrinsic::stackrestore: {
9939 // If the save is right next to the restore, remove the restore. This can
9940 // happen when variable allocas are DCE'd.
9941 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9942 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9943 BasicBlock::iterator BI = SS;
9944 if (&*++BI == II)
9945 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009946 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009947 }
9948
9949 // Scan down this block to see if there is another stack restore in the
9950 // same block without an intervening call/alloca.
9951 BasicBlock::iterator BI = II;
9952 TerminatorInst *TI = II->getParent()->getTerminator();
9953 bool CannotRemove = false;
9954 for (++BI; &*BI != TI; ++BI) {
9955 if (isa<AllocaInst>(BI)) {
9956 CannotRemove = true;
9957 break;
9958 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009959 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9960 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9961 // If there is a stackrestore below this one, remove this one.
9962 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9963 return EraseInstFromFunction(CI);
9964 // Otherwise, ignore the intrinsic.
9965 } else {
9966 // If we found a non-intrinsic call, we can't remove the stack
9967 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009968 CannotRemove = true;
9969 break;
9970 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009971 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009972 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009973
9974 // If the stack restore is in a return/unwind block and if there are no
9975 // allocas or calls between the restore and the return, nuke the restore.
9976 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9977 return EraseInstFromFunction(CI);
9978 break;
9979 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009980 }
9981
Chris Lattner8b0ea312006-01-13 20:11:04 +00009982 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009983}
9984
9985// InvokeInst simplification
9986//
9987Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009988 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009989}
9990
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009991/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9992/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009993static bool isSafeToEliminateVarargsCast(const CallSite CS,
9994 const CastInst * const CI,
9995 const TargetData * const TD,
9996 const int ix) {
9997 if (!CI->isLosslessCast())
9998 return false;
9999
10000 // The size of ByVal arguments is derived from the type, so we
10001 // can't change to a type with a different size. If the size were
10002 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010003 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010004 return true;
10005
10006 const Type* SrcTy =
10007 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10008 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10009 if (!SrcTy->isSized() || !DstTy->isSized())
10010 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010011 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010012 return false;
10013 return true;
10014}
10015
Chris Lattnera44d8a22003-10-07 22:32:43 +000010016// visitCallSite - Improvements for call and invoke instructions.
10017//
10018Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010019 bool Changed = false;
10020
10021 // If the callee is a constexpr cast of a function, attempt to move the cast
10022 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010023 if (transformConstExprCastCall(CS)) return 0;
10024
Chris Lattner6c266db2003-10-07 22:54:13 +000010025 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010026
Chris Lattner08b22ec2005-05-13 07:09:09 +000010027 if (Function *CalleeF = dyn_cast<Function>(Callee))
10028 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10029 Instruction *OldCall = CS.getInstruction();
10030 // If the call and callee calling conventions don't match, this call must
10031 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010032 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010033 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10034 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010035 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010036 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010037 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10038 return EraseInstFromFunction(*OldCall);
10039 return 0;
10040 }
10041
Chris Lattner17be6352004-10-18 02:59:09 +000010042 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10043 // This instruction is not reachable, just remove it. We insert a store to
10044 // undef so that we know that this code is not reachable, despite the fact
10045 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010046 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010047 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010048 CS.getInstruction());
10049
10050 if (!CS.getInstruction()->use_empty())
10051 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010052 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010053
10054 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10055 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010056 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010057 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010058 }
Chris Lattner17be6352004-10-18 02:59:09 +000010059 return EraseInstFromFunction(*CS.getInstruction());
10060 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010061
Duncan Sandscdb6d922007-09-17 10:26:40 +000010062 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10063 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10064 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10065 return transformCallThroughTrampoline(CS);
10066
Chris Lattner6c266db2003-10-07 22:54:13 +000010067 const PointerType *PTy = cast<PointerType>(Callee->getType());
10068 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10069 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010070 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010071 // See if we can optimize any arguments passed through the varargs area of
10072 // the call.
10073 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010074 E = CS.arg_end(); I != E; ++I, ++ix) {
10075 CastInst *CI = dyn_cast<CastInst>(*I);
10076 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10077 *I = CI->getOperand(0);
10078 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010079 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010080 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010081 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010082
Duncan Sandsf0c33542007-12-19 21:13:37 +000010083 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010084 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010085 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010086 Changed = true;
10087 }
10088
Chris Lattner6c266db2003-10-07 22:54:13 +000010089 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010090}
10091
Chris Lattner9fe38862003-06-19 17:00:31 +000010092// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10093// attempt to move the cast to the arguments of the call/invoke.
10094//
10095bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10096 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10097 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010098 if (CE->getOpcode() != Instruction::BitCast ||
10099 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010100 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010101 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010102 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010103 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010104
10105 // Okay, this is a cast from a function to a different type. Unless doing so
10106 // would cause a type conversion of one of our arguments, change this call to
10107 // be a direct call with arguments casted to the appropriate types.
10108 //
10109 const FunctionType *FT = Callee->getFunctionType();
10110 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010111 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010112
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010113 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010114 return false; // TODO: Handle multiple return values.
10115
Chris Lattnerf78616b2004-01-14 06:06:08 +000010116 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010117 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010118 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010119 // Conversion is ok if changing from one pointer type to another or from
10120 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010121 !((isa<PointerType>(OldRetTy) || !TD ||
10122 OldRetTy == TD->getIntPtrType()) &&
10123 (isa<PointerType>(NewRetTy) || !TD ||
10124 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010125 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010126
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010127 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010128 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010129 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010130 return false; // Cannot transform this return value.
10131
Chris Lattner58d74912008-03-12 17:45:29 +000010132 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010133 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010134 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010135 return false; // Attribute not compatible with transformed value.
10136 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010137
Chris Lattnerf78616b2004-01-14 06:06:08 +000010138 // If the callsite is an invoke instruction, and the return value is used by
10139 // a PHI node in a successor, we cannot change the return type of the call
10140 // because there is no place to put the cast instruction (without breaking
10141 // the critical edge). Bail out in this case.
10142 if (!Caller->use_empty())
10143 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10144 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10145 UI != E; ++UI)
10146 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10147 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010148 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010149 return false;
10150 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010151
10152 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10153 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010154
Chris Lattner9fe38862003-06-19 17:00:31 +000010155 CallSite::arg_iterator AI = CS.arg_begin();
10156 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10157 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010158 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010159
10160 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010161 return false; // Cannot transform this parameter value.
10162
Devang Patel19c87462008-09-26 22:53:05 +000010163 if (CallerPAL.getParamAttributes(i + 1)
10164 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010165 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010166
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010167 // Converting from one pointer type to another or between a pointer and an
10168 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010169 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010170 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10171 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010172 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 }
10174
10175 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010176 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010177 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010178
Chris Lattner58d74912008-03-12 17:45:29 +000010179 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10180 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010181 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010182 // won't be dropping them. Check that these extra arguments have attributes
10183 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010184 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10185 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010186 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010187 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010188 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010189 return false;
10190 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010191
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 // Okay, we decided that this is a safe thing to do: go ahead and start
10193 // inserting cast instructions as necessary...
10194 std::vector<Value*> Args;
10195 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010196 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010197 attrVec.reserve(NumCommonArgs);
10198
10199 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010200 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010201
10202 // If the return value is not being used, the type may not be compatible
10203 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010204 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010205
10206 // Add the new return attributes.
10207 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010208 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010209
10210 AI = CS.arg_begin();
10211 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10212 const Type *ParamTy = FT->getParamType(i);
10213 if ((*AI)->getType() == ParamTy) {
10214 Args.push_back(*AI);
10215 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010216 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010217 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010218 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010219 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010221
10222 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010223 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010224 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010225 }
10226
10227 // If the function takes more arguments than the call was taking, add them
10228 // now...
10229 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010230 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010231
10232 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010233 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010234 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010235 cerr << "WARNING: While resolving call to function '"
10236 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010237 } else {
10238 // Add all of the arguments in their promoted form to the arg list...
10239 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10240 const Type *PTy = getPromotedType((*AI)->getType());
10241 if (PTy != (*AI)->getType()) {
10242 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010243 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10244 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010245 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010246 InsertNewInstBefore(Cast, *Caller);
10247 Args.push_back(Cast);
10248 } else {
10249 Args.push_back(*AI);
10250 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010251
Duncan Sandse1e520f2008-01-13 08:02:44 +000010252 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010253 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010254 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010255 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010257 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010258
Devang Patel19c87462008-09-26 22:53:05 +000010259 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10260 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10261
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010262 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010263 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010264
Devang Patel05988662008-09-25 21:00:45 +000010265 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010266
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 Instruction *NC;
10268 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010269 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010270 Args.begin(), Args.end(),
10271 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010272 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010273 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010274 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010275 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10276 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010277 CallInst *CI = cast<CallInst>(Caller);
10278 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010279 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010280 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010281 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010282 }
10283
Chris Lattner6934a042007-02-11 01:23:03 +000010284 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010285 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010286 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010287 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010288 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010289 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010290 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010291
10292 // If this is an invoke instruction, we should insert it after the first
10293 // non-phi, instruction in the normal successor block.
10294 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010295 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010296 InsertNewInstBefore(NC, *I);
10297 } else {
10298 // Otherwise, it's a call, just insert cast right after the call instr
10299 InsertNewInstBefore(NC, *Caller);
10300 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010301 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010302 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010303 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010304 }
10305 }
10306
10307 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10308 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010309 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010310 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010311 return true;
10312}
10313
Duncan Sandscdb6d922007-09-17 10:26:40 +000010314// transformCallThroughTrampoline - Turn a call to a function created by the
10315// init_trampoline intrinsic into a direct call to the underlying function.
10316//
10317Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10318 Value *Callee = CS.getCalledValue();
10319 const PointerType *PTy = cast<PointerType>(Callee->getType());
10320 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010321 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010322
10323 // If the call already has the 'nest' attribute somewhere then give up -
10324 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010325 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010326 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327
10328 IntrinsicInst *Tramp =
10329 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10330
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010331 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10333 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10334
Devang Patel05988662008-09-25 21:00:45 +000010335 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010336 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337 unsigned NestIdx = 1;
10338 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010339 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010340
10341 // Look for a parameter marked with the 'nest' attribute.
10342 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10343 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010344 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010345 // Record the parameter type and any other attributes.
10346 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010347 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 break;
10349 }
10350
10351 if (NestTy) {
10352 Instruction *Caller = CS.getInstruction();
10353 std::vector<Value*> NewArgs;
10354 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10355
Devang Patel05988662008-09-25 21:00:45 +000010356 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010357 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010358
Duncan Sandscdb6d922007-09-17 10:26:40 +000010359 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010360 // mean appending it. Likewise for attributes.
10361
Devang Patel19c87462008-09-26 22:53:05 +000010362 // Add any result attributes.
10363 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010364 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010365
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366 {
10367 unsigned Idx = 1;
10368 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10369 do {
10370 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010371 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 Value *NestVal = Tramp->getOperand(3);
10373 if (NestVal->getType() != NestTy)
10374 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10375 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010376 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010377 }
10378
10379 if (I == E)
10380 break;
10381
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010382 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010384 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010385 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010386 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387
10388 ++Idx, ++I;
10389 } while (1);
10390 }
10391
Devang Patel19c87462008-09-26 22:53:05 +000010392 // Add any function attributes.
10393 if (Attributes Attr = Attrs.getFnAttributes())
10394 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10395
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 // The trampoline may have been bitcast to a bogus type (FTy).
10397 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 NewTypes.reserve(FTy->getNumParams()+1);
10402
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 {
10406 unsigned Idx = 1;
10407 FunctionType::param_iterator I = FTy->param_begin(),
10408 E = FTy->param_end();
10409
10410 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010411 if (Idx == NestIdx)
10412 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414
10415 if (I == E)
10416 break;
10417
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010418 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010419 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420
10421 ++Idx, ++I;
10422 } while (1);
10423 }
10424
10425 // Replace the trampoline call with a direct call. Let the generic
10426 // code sort out any function type mismatches.
10427 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010428 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10429 FTy->isVarArg());
10430 Constant *NewCallee =
10431 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10432 NestF : Context->getConstantExprBitCast(NestF,
10433 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010434 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435
10436 Instruction *NewCaller;
10437 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010438 NewCaller = InvokeInst::Create(NewCallee,
10439 II->getNormalDest(), II->getUnwindDest(),
10440 NewArgs.begin(), NewArgs.end(),
10441 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010443 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010445 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10446 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010447 if (cast<CallInst>(Caller)->isTailCall())
10448 cast<CallInst>(NewCaller)->setTailCall();
10449 cast<CallInst>(NewCaller)->
10450 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010451 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 }
10453 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10454 Caller->replaceAllUsesWith(NewCaller);
10455 Caller->eraseFromParent();
10456 RemoveFromWorkList(Caller);
10457 return 0;
10458 }
10459 }
10460
10461 // Replace the trampoline call with a direct call. Since there is no 'nest'
10462 // parameter, there is no need to adjust the argument list. Let the generic
10463 // code sort out any function type mismatches.
10464 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010465 NestF->getType() == PTy ? NestF :
10466 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010467 CS.setCalledFunction(NewCallee);
10468 return CS.getInstruction();
10469}
10470
Chris Lattner7da52b22006-11-01 04:51:18 +000010471/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10472/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10473/// and a single binop.
10474Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10475 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010476 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010477 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010478 Value *LHSVal = FirstInst->getOperand(0);
10479 Value *RHSVal = FirstInst->getOperand(1);
10480
10481 const Type *LHSType = LHSVal->getType();
10482 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010483
10484 // Scan to see if all operands are the same opcode, all have one use, and all
10485 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010486 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010487 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010488 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010489 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010490 // types or GEP's with different index types.
10491 I->getOperand(0)->getType() != LHSType ||
10492 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010493 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010494
10495 // If they are CmpInst instructions, check their predicates
10496 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10497 if (cast<CmpInst>(I)->getPredicate() !=
10498 cast<CmpInst>(FirstInst)->getPredicate())
10499 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010500
10501 // Keep track of which operand needs a phi node.
10502 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10503 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010504 }
10505
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010506 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010507
Chris Lattner7da52b22006-11-01 04:51:18 +000010508 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010509 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010510 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010511 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010512 NewLHS = PHINode::Create(LHSType,
10513 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010514 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10515 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010516 InsertNewInstBefore(NewLHS, PN);
10517 LHSVal = NewLHS;
10518 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010519
10520 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010521 NewRHS = PHINode::Create(RHSType,
10522 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010523 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10524 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010525 InsertNewInstBefore(NewRHS, PN);
10526 RHSVal = NewRHS;
10527 }
10528
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010529 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010530 if (NewLHS || NewRHS) {
10531 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10532 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10533 if (NewLHS) {
10534 Value *NewInLHS = InInst->getOperand(0);
10535 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10536 }
10537 if (NewRHS) {
10538 Value *NewInRHS = InInst->getOperand(1);
10539 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10540 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010541 }
10542 }
10543
Chris Lattner7da52b22006-11-01 04:51:18 +000010544 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010545 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010546 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010547 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10548 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010549}
10550
Chris Lattner05f18922008-12-01 02:34:36 +000010551Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10552 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10553
10554 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10555 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010556 // This is true if all GEP bases are allocas and if all indices into them are
10557 // constants.
10558 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010559
10560 // Scan to see if all operands are the same opcode, all have one use, and all
10561 // kill their operands (i.e. the operands have one use).
10562 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10563 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10564 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10565 GEP->getNumOperands() != FirstInst->getNumOperands())
10566 return 0;
10567
Chris Lattner36d3e322009-02-21 00:46:50 +000010568 // Keep track of whether or not all GEPs are of alloca pointers.
10569 if (AllBasePointersAreAllocas &&
10570 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10571 !GEP->hasAllConstantIndices()))
10572 AllBasePointersAreAllocas = false;
10573
Chris Lattner05f18922008-12-01 02:34:36 +000010574 // Compare the operand lists.
10575 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10576 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10577 continue;
10578
10579 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10580 // if one of the PHIs has a constant for the index. The index may be
10581 // substantially cheaper to compute for the constants, so making it a
10582 // variable index could pessimize the path. This also handles the case
10583 // for struct indices, which must always be constant.
10584 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10585 isa<ConstantInt>(GEP->getOperand(op)))
10586 return 0;
10587
10588 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10589 return 0;
10590 FixedOperands[op] = 0; // Needs a PHI.
10591 }
10592 }
10593
Chris Lattner36d3e322009-02-21 00:46:50 +000010594 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010595 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010596 // offset calculation, but all the predecessors will have to materialize the
10597 // stack address into a register anyway. We'd actually rather *clone* the
10598 // load up into the predecessors so that we have a load of a gep of an alloca,
10599 // which can usually all be folded into the load.
10600 if (AllBasePointersAreAllocas)
10601 return 0;
10602
Chris Lattner05f18922008-12-01 02:34:36 +000010603 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10604 // that is variable.
10605 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10606
10607 bool HasAnyPHIs = false;
10608 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10609 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10610 Value *FirstOp = FirstInst->getOperand(i);
10611 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10612 FirstOp->getName()+".pn");
10613 InsertNewInstBefore(NewPN, PN);
10614
10615 NewPN->reserveOperandSpace(e);
10616 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10617 OperandPhis[i] = NewPN;
10618 FixedOperands[i] = NewPN;
10619 HasAnyPHIs = true;
10620 }
10621
10622
10623 // Add all operands to the new PHIs.
10624 if (HasAnyPHIs) {
10625 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10626 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10627 BasicBlock *InBB = PN.getIncomingBlock(i);
10628
10629 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10630 if (PHINode *OpPhi = OperandPhis[op])
10631 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10632 }
10633 }
10634
10635 Value *Base = FixedOperands[0];
10636 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10637 FixedOperands.end());
10638}
10639
10640
Chris Lattner21550882009-02-23 05:56:17 +000010641/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10642/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010643/// obvious the value of the load is not changed from the point of the load to
10644/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010645///
10646/// Finally, it is safe, but not profitable, to sink a load targetting a
10647/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10648/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010649static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010650 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10651
10652 for (++BBI; BBI != E; ++BBI)
10653 if (BBI->mayWriteToMemory())
10654 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010655
10656 // Check for non-address taken alloca. If not address-taken already, it isn't
10657 // profitable to do this xform.
10658 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10659 bool isAddressTaken = false;
10660 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10661 UI != E; ++UI) {
10662 if (isa<LoadInst>(UI)) continue;
10663 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10664 // If storing TO the alloca, then the address isn't taken.
10665 if (SI->getOperand(1) == AI) continue;
10666 }
10667 isAddressTaken = true;
10668 break;
10669 }
10670
Chris Lattner36d3e322009-02-21 00:46:50 +000010671 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010672 return false;
10673 }
10674
Chris Lattner36d3e322009-02-21 00:46:50 +000010675 // If this load is a load from a GEP with a constant offset from an alloca,
10676 // then we don't want to sink it. In its present form, it will be
10677 // load [constant stack offset]. Sinking it will cause us to have to
10678 // materialize the stack addresses in each predecessor in a register only to
10679 // do a shared load from register in the successor.
10680 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10681 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10682 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10683 return false;
10684
Chris Lattner76c73142006-11-01 07:13:54 +000010685 return true;
10686}
10687
Chris Lattner9fe38862003-06-19 17:00:31 +000010688
Chris Lattnerbac32862004-11-14 19:13:23 +000010689// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10690// operator and they all are only used by the PHI, PHI together their
10691// inputs, and do the operation once, to the result of the PHI.
10692Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10693 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10694
10695 // Scan the instruction, looking for input operations that can be folded away.
10696 // If all input operands to the phi are the same instruction (e.g. a cast from
10697 // the same type or "+42") we can pull the operation through the PHI, reducing
10698 // code size and simplifying code.
10699 Constant *ConstantOp = 0;
10700 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010701 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010702 if (isa<CastInst>(FirstInst)) {
10703 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010704 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010705 // Can fold binop, compare or shift here if the RHS is a constant,
10706 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010707 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010708 if (ConstantOp == 0)
10709 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010710 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10711 isVolatile = LI->isVolatile();
10712 // We can't sink the load if the loaded value could be modified between the
10713 // load and the PHI.
10714 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010715 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010716 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010717
10718 // If the PHI is of volatile loads and the load block has multiple
10719 // successors, sinking it would remove a load of the volatile value from
10720 // the path through the other successor.
10721 if (isVolatile &&
10722 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10723 return 0;
10724
Chris Lattner9c080502006-11-01 07:43:41 +000010725 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010726 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010727 } else {
10728 return 0; // Cannot fold this operation.
10729 }
10730
10731 // Check to see if all arguments are the same operation.
10732 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10733 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10734 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010735 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010736 return 0;
10737 if (CastSrcTy) {
10738 if (I->getOperand(0)->getType() != CastSrcTy)
10739 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010740 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010741 // We can't sink the load if the loaded value could be modified between
10742 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010743 if (LI->isVolatile() != isVolatile ||
10744 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010745 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010746 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010747
Chris Lattner71042962008-07-08 17:18:32 +000010748 // If the PHI is of volatile loads and the load block has multiple
10749 // successors, sinking it would remove a load of the volatile value from
10750 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010751 if (isVolatile &&
10752 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10753 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010754
Chris Lattnerbac32862004-11-14 19:13:23 +000010755 } else if (I->getOperand(1) != ConstantOp) {
10756 return 0;
10757 }
10758 }
10759
10760 // Okay, they are all the same operation. Create a new PHI node of the
10761 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010762 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10763 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010764 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010765
10766 Value *InVal = FirstInst->getOperand(0);
10767 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010768
10769 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010770 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10771 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10772 if (NewInVal != InVal)
10773 InVal = 0;
10774 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10775 }
10776
10777 Value *PhiVal;
10778 if (InVal) {
10779 // The new PHI unions all of the same values together. This is really
10780 // common, so we handle it intelligently here for compile-time speed.
10781 PhiVal = InVal;
10782 delete NewPN;
10783 } else {
10784 InsertNewInstBefore(NewPN, PN);
10785 PhiVal = NewPN;
10786 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010787
Chris Lattnerbac32862004-11-14 19:13:23 +000010788 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010789 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010790 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010791 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010792 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010793 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010794 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010795 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010796 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10797
10798 // If this was a volatile load that we are merging, make sure to loop through
10799 // and mark all the input loads as non-volatile. If we don't do this, we will
10800 // insert a new volatile load and the old ones will not be deletable.
10801 if (isVolatile)
10802 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10803 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10804
10805 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010806}
Chris Lattnera1be5662002-05-02 17:06:02 +000010807
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010808/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10809/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010810static bool DeadPHICycle(PHINode *PN,
10811 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010812 if (PN->use_empty()) return true;
10813 if (!PN->hasOneUse()) return false;
10814
10815 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010816 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010817 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010818
10819 // Don't scan crazily complex things.
10820 if (PotentiallyDeadPHIs.size() == 16)
10821 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010822
10823 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10824 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010825
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010826 return false;
10827}
10828
Chris Lattnercf5008a2007-11-06 21:52:06 +000010829/// PHIsEqualValue - Return true if this phi node is always equal to
10830/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10831/// z = some value; x = phi (y, z); y = phi (x, z)
10832static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10833 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10834 // See if we already saw this PHI node.
10835 if (!ValueEqualPHIs.insert(PN))
10836 return true;
10837
10838 // Don't scan crazily complex things.
10839 if (ValueEqualPHIs.size() == 16)
10840 return false;
10841
10842 // Scan the operands to see if they are either phi nodes or are equal to
10843 // the value.
10844 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10845 Value *Op = PN->getIncomingValue(i);
10846 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10847 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10848 return false;
10849 } else if (Op != NonPhiInVal)
10850 return false;
10851 }
10852
10853 return true;
10854}
10855
10856
Chris Lattner473945d2002-05-06 18:06:38 +000010857// PHINode simplification
10858//
Chris Lattner7e708292002-06-25 16:13:24 +000010859Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010860 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010861 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010862
Owen Anderson7e057142006-07-10 22:03:18 +000010863 if (Value *V = PN.hasConstantValue())
10864 return ReplaceInstUsesWith(PN, V);
10865
Owen Anderson7e057142006-07-10 22:03:18 +000010866 // If all PHI operands are the same operation, pull them through the PHI,
10867 // reducing code size.
10868 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010869 isa<Instruction>(PN.getIncomingValue(1)) &&
10870 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10871 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10872 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10873 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010874 PN.getIncomingValue(0)->hasOneUse())
10875 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10876 return Result;
10877
10878 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10879 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10880 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010881 if (PN.hasOneUse()) {
10882 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10883 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010884 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010885 PotentiallyDeadPHIs.insert(&PN);
10886 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010887 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010888 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010889
10890 // If this phi has a single use, and if that use just computes a value for
10891 // the next iteration of a loop, delete the phi. This occurs with unused
10892 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10893 // common case here is good because the only other things that catch this
10894 // are induction variable analysis (sometimes) and ADCE, which is only run
10895 // late.
10896 if (PHIUser->hasOneUse() &&
10897 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10898 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010899 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010900 }
10901 }
Owen Anderson7e057142006-07-10 22:03:18 +000010902
Chris Lattnercf5008a2007-11-06 21:52:06 +000010903 // We sometimes end up with phi cycles that non-obviously end up being the
10904 // same value, for example:
10905 // z = some value; x = phi (y, z); y = phi (x, z)
10906 // where the phi nodes don't necessarily need to be in the same block. Do a
10907 // quick check to see if the PHI node only contains a single non-phi value, if
10908 // so, scan to see if the phi cycle is actually equal to that value.
10909 {
10910 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10911 // Scan for the first non-phi operand.
10912 while (InValNo != NumOperandVals &&
10913 isa<PHINode>(PN.getIncomingValue(InValNo)))
10914 ++InValNo;
10915
10916 if (InValNo != NumOperandVals) {
10917 Value *NonPhiInVal = PN.getOperand(InValNo);
10918
10919 // Scan the rest of the operands to see if there are any conflicts, if so
10920 // there is no need to recursively scan other phis.
10921 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10922 Value *OpVal = PN.getIncomingValue(InValNo);
10923 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10924 break;
10925 }
10926
10927 // If we scanned over all operands, then we have one unique value plus
10928 // phi values. Scan PHI nodes to see if they all merge in each other or
10929 // the value.
10930 if (InValNo == NumOperandVals) {
10931 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10932 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10933 return ReplaceInstUsesWith(PN, NonPhiInVal);
10934 }
10935 }
10936 }
Chris Lattner60921c92003-12-19 05:58:40 +000010937 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010938}
10939
Reid Spencer17212df2006-12-12 09:18:51 +000010940static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10941 Instruction *InsertPoint,
10942 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010943 unsigned PtrSize = DTy->getScalarSizeInBits();
10944 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010945 // We must cast correctly to the pointer type. Ensure that we
10946 // sign extend the integer value if it is smaller as this is
10947 // used for address computation.
10948 Instruction::CastOps opcode =
10949 (VTySize < PtrSize ? Instruction::SExt :
10950 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10951 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010952}
10953
Chris Lattnera1be5662002-05-02 17:06:02 +000010954
Chris Lattner7e708292002-06-25 16:13:24 +000010955Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010956 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010957 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010958 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010959 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010960 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010961
Chris Lattnere87597f2004-10-16 18:11:37 +000010962 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000010963 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010964
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010965 bool HasZeroPointerIndex = false;
10966 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10967 HasZeroPointerIndex = C->isNullValue();
10968
10969 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010970 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010971
Chris Lattner28977af2004-04-05 01:30:19 +000010972 // Eliminate unneeded casts for indices.
10973 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010974
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010975 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010976 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10977 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010978 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010979 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010980 if (CI->getOpcode() == Instruction::ZExt ||
10981 CI->getOpcode() == Instruction::SExt) {
10982 const Type *SrcTy = CI->getOperand(0)->getType();
10983 // We can eliminate a cast from i32 to i64 iff the target
10984 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010985 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010986 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010987 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010988 }
10989 }
10990 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010991 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010992 // to what we need. If narrower, sign-extend it to what we need.
10993 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010994 // insert it. This explicit cast can make subsequent optimizations more
10995 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010996 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010997 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010998 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010999 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011000 MadeChange = true;
11001 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011002 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11003 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011004 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011005 MadeChange = true;
11006 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011007 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11008 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011009 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011010 MadeChange = true;
11011 } else {
11012 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11013 GEP);
11014 *i = Op;
11015 MadeChange = true;
11016 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011017 }
Chris Lattner28977af2004-04-05 01:30:19 +000011018 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011019 }
Chris Lattner28977af2004-04-05 01:30:19 +000011020 if (MadeChange) return &GEP;
11021
Chris Lattner90ac28c2002-08-02 19:29:35 +000011022 // Combine Indices - If the source pointer to this getelementptr instruction
11023 // is a getelementptr instruction, combine the indices of the two
11024 // getelementptr instructions into a single instruction.
11025 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011026 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011027 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011028 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011029
11030 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011031 // Note that if our source is a gep chain itself that we wait for that
11032 // chain to be resolved before we perform this transformation. This
11033 // avoids us creating a TON of code in some cases.
11034 //
11035 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11036 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11037 return 0; // Wait until our source is folded to completion.
11038
Chris Lattner72588fc2007-02-15 22:48:32 +000011039 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011040
11041 // Find out whether the last index in the source GEP is a sequential idx.
11042 bool EndsWithSequential = false;
11043 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11044 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011045 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011046
Chris Lattner90ac28c2002-08-02 19:29:35 +000011047 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011048 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011049 // Replace: gep (gep %P, long B), long A, ...
11050 // With: T = long A+B; gep %P, T, ...
11051 //
Chris Lattner620ce142004-05-07 22:09:22 +000011052 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011053 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011054 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011055 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011056 Sum = SO1;
11057 } else {
11058 // If they aren't the same type, convert both to an integer of the
11059 // target's pointer size.
11060 if (SO1->getType() != GO1->getType()) {
11061 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011062 SO1 =
11063 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011064 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011065 GO1 =
11066 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011067 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011068 unsigned PS = TD->getPointerSizeInBits();
11069 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011070 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011071 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011072
Duncan Sands514ab342007-11-01 20:53:16 +000011073 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011074 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011075 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011076 } else {
11077 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011078 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11079 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011080 }
11081 }
11082 }
Chris Lattner620ce142004-05-07 22:09:22 +000011083 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011084 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11085 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011086 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011087 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011088 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011089 }
Chris Lattner28977af2004-04-05 01:30:19 +000011090 }
Chris Lattner620ce142004-05-07 22:09:22 +000011091
11092 // Recycle the GEP we already have if possible.
11093 if (SrcGEPOperands.size() == 2) {
11094 GEP.setOperand(0, SrcGEPOperands[0]);
11095 GEP.setOperand(1, Sum);
11096 return &GEP;
11097 } else {
11098 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11099 SrcGEPOperands.end()-1);
11100 Indices.push_back(Sum);
11101 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11102 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011103 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011104 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011105 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011106 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011107 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11108 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011109 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11110 }
11111
11112 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011113 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11114 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011115
Chris Lattner620ce142004-05-07 22:09:22 +000011116 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011117 // GEP of global variable. If all of the indices for this GEP are
11118 // constants, we can promote this to a constexpr instead of an instruction.
11119
11120 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011121 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011122 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11123 for (; I != E && isa<Constant>(*I); ++I)
11124 Indices.push_back(cast<Constant>(*I));
11125
11126 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011127 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011128 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011129
11130 // Replace all uses of the GEP with the new constexpr...
11131 return ReplaceInstUsesWith(GEP, CE);
11132 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011133 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011134 if (!isa<PointerType>(X->getType())) {
11135 // Not interesting. Source pointer must be a cast from pointer.
11136 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011137 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11138 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011139 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011140 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11141 // into : GEP i8* X, ...
11142 //
Chris Lattnereed48272005-09-13 00:40:14 +000011143 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011144 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11145 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011146 if (const ArrayType *CATy =
11147 dyn_cast<ArrayType>(CPTy->getElementType())) {
11148 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11149 if (CATy->getElementType() == XTy->getElementType()) {
11150 // -> GEP i8* X, ...
11151 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11152 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11153 GEP.getName());
11154 } else if (const ArrayType *XATy =
11155 dyn_cast<ArrayType>(XTy->getElementType())) {
11156 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011157 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011158 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011159 // At this point, we know that the cast source type is a pointer
11160 // to an array of the same type as the destination pointer
11161 // array. Because the array type is never stepped over (there
11162 // is a leading zero) we can fold the cast into this GEP.
11163 GEP.setOperand(0, X);
11164 return &GEP;
11165 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011166 }
11167 }
Chris Lattnereed48272005-09-13 00:40:14 +000011168 } else if (GEP.getNumOperands() == 2) {
11169 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011170 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11171 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011172 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11173 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011174 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011175 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11176 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011177 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011178 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011179 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011180 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011181 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011182 // V and GEP are both pointer types --> BitCast
11183 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011184 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011185
11186 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011187 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011188 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011189 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011190
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011191 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011192 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011193 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011194
11195 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11196 // allow either a mul, shift, or constant here.
11197 Value *NewIdx = 0;
11198 ConstantInt *Scale = 0;
11199 if (ArrayEltSize == 1) {
11200 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011201 Scale =
11202 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011203 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011204 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011205 Scale = CI;
11206 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11207 if (Inst->getOpcode() == Instruction::Shl &&
11208 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011209 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11210 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011211 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011212 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011213 NewIdx = Inst->getOperand(0);
11214 } else if (Inst->getOpcode() == Instruction::Mul &&
11215 isa<ConstantInt>(Inst->getOperand(1))) {
11216 Scale = cast<ConstantInt>(Inst->getOperand(1));
11217 NewIdx = Inst->getOperand(0);
11218 }
11219 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011220
Chris Lattner7835cdd2005-09-13 18:36:04 +000011221 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011222 // out, perform the transformation. Note, we don't know whether Scale is
11223 // signed or not. We'll use unsigned version of division/modulo
11224 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011225 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011226 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011227 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011228 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011229 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011230 Constant *C =
11231 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011232 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011233 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011234 NewIdx = InsertNewInstBefore(Sc, GEP);
11235 }
11236
11237 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011238 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011239 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011240 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011241 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011242 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011243 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11244 // The NewGEP must be pointer typed, so must the old one -> BitCast
11245 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011246 }
11247 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011248 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011249 }
Chris Lattner58407792009-01-09 04:53:57 +000011250
Chris Lattner46cd5a12009-01-09 05:44:56 +000011251 /// See if we can simplify:
11252 /// X = bitcast A to B*
11253 /// Y = gep X, <...constant indices...>
11254 /// into a gep of the original struct. This is important for SROA and alias
11255 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011256 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011257 if (TD &&
11258 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011259 // Determine how much the GEP moves the pointer. We are guaranteed to get
11260 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011261 ConstantInt *OffsetV =
11262 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011263 int64_t Offset = OffsetV->getSExtValue();
11264
11265 // If this GEP instruction doesn't move the pointer, just replace the GEP
11266 // with a bitcast of the real input to the dest type.
11267 if (Offset == 0) {
11268 // If the bitcast is of an allocation, and the allocation will be
11269 // converted to match the type of the cast, don't touch this.
11270 if (isa<AllocationInst>(BCI->getOperand(0))) {
11271 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11272 if (Instruction *I = visitBitCast(*BCI)) {
11273 if (I != BCI) {
11274 I->takeName(BCI);
11275 BCI->getParent()->getInstList().insert(BCI, I);
11276 ReplaceInstUsesWith(*BCI, I);
11277 }
11278 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011279 }
Chris Lattner58407792009-01-09 04:53:57 +000011280 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011281 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011282 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011283
11284 // Otherwise, if the offset is non-zero, we need to find out if there is a
11285 // field at Offset in 'A's type. If so, we can pull the cast through the
11286 // GEP.
11287 SmallVector<Value*, 8> NewIndices;
11288 const Type *InTy =
11289 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011290 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011291 Instruction *NGEP =
11292 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11293 NewIndices.end());
11294 if (NGEP->getType() == GEP.getType()) return NGEP;
11295 InsertNewInstBefore(NGEP, GEP);
11296 NGEP->takeName(&GEP);
11297 return new BitCastInst(NGEP, GEP.getType());
11298 }
Chris Lattner58407792009-01-09 04:53:57 +000011299 }
11300 }
11301
Chris Lattner8a2a3112001-12-14 16:52:21 +000011302 return 0;
11303}
11304
Chris Lattner0864acf2002-11-04 16:18:53 +000011305Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11306 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011307 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011308 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11309 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011310 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011311 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011312
11313 // Create and insert the replacement instruction...
11314 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011315 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011316 else {
11317 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011318 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011319 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011320
11321 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011322
Chris Lattner0864acf2002-11-04 16:18:53 +000011323 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011324 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011325 //
11326 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011327 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011328
11329 // Now that I is pointing to the first non-allocation-inst in the block,
11330 // insert our getelementptr instruction...
11331 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011332 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011333 Value *Idx[2];
11334 Idx[0] = NullIdx;
11335 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011336 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11337 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011338
11339 // Now make everything use the getelementptr instead of the original
11340 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011341 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011342 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011343 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011344 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011345 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011346
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011347 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011348 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011349 // Note that we only do this for alloca's, because malloc should allocate
11350 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011351 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011352 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011353
11354 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11355 if (AI.getAlignment() == 0)
11356 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11357 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011358
Chris Lattner0864acf2002-11-04 16:18:53 +000011359 return 0;
11360}
11361
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011362Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11363 Value *Op = FI.getOperand(0);
11364
Chris Lattner17be6352004-10-18 02:59:09 +000011365 // free undef -> unreachable.
11366 if (isa<UndefValue>(Op)) {
11367 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011368 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011369 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011370 return EraseInstFromFunction(FI);
11371 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011372
Chris Lattner6160e852004-02-28 04:57:37 +000011373 // If we have 'free null' delete the instruction. This can happen in stl code
11374 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011375 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011376 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011377
11378 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11379 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11380 FI.setOperand(0, CI->getOperand(0));
11381 return &FI;
11382 }
11383
11384 // Change free (gep X, 0,0,0,0) into free(X)
11385 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11386 if (GEPI->hasAllZeroIndices()) {
11387 AddToWorkList(GEPI);
11388 FI.setOperand(0, GEPI->getOperand(0));
11389 return &FI;
11390 }
11391 }
11392
11393 // Change free(malloc) into nothing, if the malloc has a single use.
11394 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11395 if (MI->hasOneUse()) {
11396 EraseInstFromFunction(FI);
11397 return EraseInstFromFunction(*MI);
11398 }
Chris Lattner6160e852004-02-28 04:57:37 +000011399
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011400 return 0;
11401}
11402
11403
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011404/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011405static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011406 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011407 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011408 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011409 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011410
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011411 if (TD) {
11412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11413 // Instead of loading constant c string, use corresponding integer value
11414 // directly if string length is small enough.
11415 std::string Str;
11416 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11417 unsigned len = Str.length();
11418 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11419 unsigned numBits = Ty->getPrimitiveSizeInBits();
11420 // Replace LI with immediate integer store.
11421 if ((numBits >> 3) == len + 1) {
11422 APInt StrVal(numBits, 0);
11423 APInt SingleChar(numBits, 0);
11424 if (TD->isLittleEndian()) {
11425 for (signed i = len-1; i >= 0; i--) {
11426 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11427 StrVal = (StrVal << 8) | SingleChar;
11428 }
11429 } else {
11430 for (unsigned i = 0; i < len; i++) {
11431 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11432 StrVal = (StrVal << 8) | SingleChar;
11433 }
11434 // Append NULL at the end.
11435 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011436 StrVal = (StrVal << 8) | SingleChar;
11437 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011438 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011439 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011440 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011441 }
11442 }
11443 }
11444
Mon P Wang6753f952009-02-07 22:19:29 +000011445 const PointerType *DestTy = cast<PointerType>(CI->getType());
11446 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011447 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011448
11449 // If the address spaces don't match, don't eliminate the cast.
11450 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11451 return 0;
11452
Chris Lattnerb89e0712004-07-13 01:49:43 +000011453 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011454
Reid Spencer42230162007-01-22 05:51:25 +000011455 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011456 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011457 // If the source is an array, the code below will not succeed. Check to
11458 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11459 // constants.
11460 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11461 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11462 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011463 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011464 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11465 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011466 SrcTy = cast<PointerType>(CastOp->getType());
11467 SrcPTy = SrcTy->getElementType();
11468 }
11469
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011470 if (IC.getTargetData() &&
11471 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011472 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011473 // Do not allow turning this into a load of an integer, which is then
11474 // casted to a pointer, this pessimizes pointer analysis a lot.
11475 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011476 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11477 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011478
Chris Lattnerf9527852005-01-31 04:50:46 +000011479 // Okay, we are casting from one integer or pointer type to another of
11480 // the same size. Instead of casting the pointer before the load, cast
11481 // the result of the loaded value.
11482 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11483 CI->getName(),
11484 LI.isVolatile()),LI);
11485 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011486 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011487 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011488 }
11489 }
11490 return 0;
11491}
11492
Chris Lattner833b8a42003-06-26 05:06:25 +000011493Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11494 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011495
Dan Gohman9941f742007-07-20 16:34:21 +000011496 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011497 if (TD) {
11498 unsigned KnownAlign =
11499 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11500 if (KnownAlign >
11501 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11502 LI.getAlignment()))
11503 LI.setAlignment(KnownAlign);
11504 }
Dan Gohman9941f742007-07-20 16:34:21 +000011505
Chris Lattner37366c12005-05-01 04:24:53 +000011506 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011507 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011508 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011509 return Res;
11510
11511 // None of the following transforms are legal for volatile loads.
11512 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011513
Dan Gohman2276a7b2008-10-15 23:19:35 +000011514 // Do really simple store-to-load forwarding and load CSE, to catch cases
11515 // where there are several consequtive memory accesses to the same location,
11516 // separated by a few arithmetic operations.
11517 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011518 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11519 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011520
Christopher Lambb15147e2007-12-29 07:56:53 +000011521 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11522 const Value *GEPI0 = GEPI->getOperand(0);
11523 // TODO: Consider a target hook for valid address spaces for this xform.
11524 if (isa<ConstantPointerNull>(GEPI0) &&
11525 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011526 // Insert a new store to null instruction before the load to indicate
11527 // that this code is not reachable. We do this instead of inserting
11528 // an unreachable instruction directly because we cannot modify the
11529 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011530 new StoreInst(Context->getUndef(LI.getType()),
11531 Context->getNullValue(Op->getType()), &LI);
11532 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011533 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011534 }
Chris Lattner37366c12005-05-01 04:24:53 +000011535
Chris Lattnere87597f2004-10-16 18:11:37 +000011536 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011537 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011538 // TODO: Consider a target hook for valid address spaces for this xform.
11539 if (isa<UndefValue>(C) || (C->isNullValue() &&
11540 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011541 // Insert a new store to null instruction before the load to indicate that
11542 // this code is not reachable. We do this instead of inserting an
11543 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011544 new StoreInst(Context->getUndef(LI.getType()),
11545 Context->getNullValue(Op->getType()), &LI);
11546 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011547 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011548
Chris Lattnere87597f2004-10-16 18:11:37 +000011549 // Instcombine load (constant global) into the value loaded.
11550 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011551 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011552 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011553
Chris Lattnere87597f2004-10-16 18:11:37 +000011554 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011556 if (CE->getOpcode() == Instruction::GetElementPtr) {
11557 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011558 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011559 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011560 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011561 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011562 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011563 if (CE->getOperand(0)->isNullValue()) {
11564 // Insert a new store to null instruction before the load to indicate
11565 // that this code is not reachable. We do this instead of inserting
11566 // an unreachable instruction directly because we cannot modify the
11567 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011568 new StoreInst(Context->getUndef(LI.getType()),
11569 Context->getNullValue(Op->getType()), &LI);
11570 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011571 }
11572
Reid Spencer3da59db2006-11-27 01:05:10 +000011573 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011574 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011575 return Res;
11576 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011577 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011578 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011579
11580 // If this load comes from anywhere in a constant global, and if the global
11581 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011582 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011583 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011584 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011585 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011586 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011587 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011588 }
11589 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011590
Chris Lattner37366c12005-05-01 04:24:53 +000011591 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011592 // Change select and PHI nodes to select values instead of addresses: this
11593 // helps alias analysis out a lot, allows many others simplifications, and
11594 // exposes redundancy in the code.
11595 //
11596 // Note that we cannot do the transformation unless we know that the
11597 // introduced loads cannot trap! Something like this is valid as long as
11598 // the condition is always false: load (select bool %C, int* null, int* %G),
11599 // but it would not be valid if we transformed it to load from null
11600 // unconditionally.
11601 //
11602 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11603 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011604 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11605 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011606 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011607 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011608 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011609 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011610 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011611 }
11612
Chris Lattner684fe212004-09-23 15:46:00 +000011613 // load (select (cond, null, P)) -> load P
11614 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11615 if (C->isNullValue()) {
11616 LI.setOperand(0, SI->getOperand(2));
11617 return &LI;
11618 }
11619
11620 // load (select (cond, P, null)) -> load P
11621 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11622 if (C->isNullValue()) {
11623 LI.setOperand(0, SI->getOperand(1));
11624 return &LI;
11625 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011626 }
11627 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011628 return 0;
11629}
11630
Reid Spencer55af2b52007-01-19 21:20:31 +000011631/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011632/// when possible. This makes it generally easy to do alias analysis and/or
11633/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011634static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11635 User *CI = cast<User>(SI.getOperand(1));
11636 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011637 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011638
11639 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011640 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11641 if (SrcTy == 0) return 0;
11642
11643 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011644
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011645 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11646 return 0;
11647
Chris Lattner3914f722009-01-24 01:00:13 +000011648 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11649 /// to its first element. This allows us to handle things like:
11650 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11651 /// on 32-bit hosts.
11652 SmallVector<Value*, 4> NewGEPIndices;
11653
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011654 // If the source is an array, the code below will not succeed. Check to
11655 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11656 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011657 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11658 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011659 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011660 NewGEPIndices.push_back(Zero);
11661
11662 while (1) {
11663 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011664 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011665 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011666 NewGEPIndices.push_back(Zero);
11667 SrcPTy = STy->getElementType(0);
11668 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11669 NewGEPIndices.push_back(Zero);
11670 SrcPTy = ATy->getElementType();
11671 } else {
11672 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011673 }
Chris Lattner3914f722009-01-24 01:00:13 +000011674 }
11675
Owen Andersond672ecb2009-07-03 00:17:18 +000011676 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011677 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011678
11679 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11680 return 0;
11681
Chris Lattner71759c42009-01-16 20:12:52 +000011682 // If the pointers point into different address spaces or if they point to
11683 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011684 if (!IC.getTargetData() ||
11685 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011686 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011687 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11688 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011689 return 0;
11690
11691 // Okay, we are casting from one integer or pointer type to another of
11692 // the same size. Instead of casting the pointer before
11693 // the store, cast the value to be stored.
11694 Value *NewCast;
11695 Value *SIOp0 = SI.getOperand(0);
11696 Instruction::CastOps opcode = Instruction::BitCast;
11697 const Type* CastSrcTy = SIOp0->getType();
11698 const Type* CastDstTy = SrcPTy;
11699 if (isa<PointerType>(CastDstTy)) {
11700 if (CastSrcTy->isInteger())
11701 opcode = Instruction::IntToPtr;
11702 } else if (isa<IntegerType>(CastDstTy)) {
11703 if (isa<PointerType>(SIOp0->getType()))
11704 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011705 }
Chris Lattner3914f722009-01-24 01:00:13 +000011706
11707 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11708 // emit a GEP to index into its first field.
11709 if (!NewGEPIndices.empty()) {
11710 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011711 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011712 NewGEPIndices.size());
11713 else
11714 CastOp = IC.InsertNewInstBefore(
11715 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11716 NewGEPIndices.end()), SI);
11717 }
11718
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011719 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011720 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011721 else
11722 NewCast = IC.InsertNewInstBefore(
11723 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11724 SI);
11725 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011726}
11727
Chris Lattner4aebaee2008-11-27 08:56:30 +000011728/// equivalentAddressValues - Test if A and B will obviously have the same
11729/// value. This includes recognizing that %t0 and %t1 will have the same
11730/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011731/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011732/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011733/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011734/// %t2 = load i32* %t1
11735///
11736static bool equivalentAddressValues(Value *A, Value *B) {
11737 // Test if the values are trivially equivalent.
11738 if (A == B) return true;
11739
11740 // Test if the values come form identical arithmetic instructions.
11741 if (isa<BinaryOperator>(A) ||
11742 isa<CastInst>(A) ||
11743 isa<PHINode>(A) ||
11744 isa<GetElementPtrInst>(A))
11745 if (Instruction *BI = dyn_cast<Instruction>(B))
11746 if (cast<Instruction>(A)->isIdenticalTo(BI))
11747 return true;
11748
11749 // Otherwise they may not be equivalent.
11750 return false;
11751}
11752
Dale Johannesen4945c652009-03-03 21:26:39 +000011753// If this instruction has two uses, one of which is a llvm.dbg.declare,
11754// return the llvm.dbg.declare.
11755DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11756 if (!V->hasNUses(2))
11757 return 0;
11758 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11759 UI != E; ++UI) {
11760 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11761 return DI;
11762 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11763 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11764 return DI;
11765 }
11766 }
11767 return 0;
11768}
11769
Chris Lattner2f503e62005-01-31 05:36:43 +000011770Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11771 Value *Val = SI.getOperand(0);
11772 Value *Ptr = SI.getOperand(1);
11773
11774 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011775 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011776 ++NumCombined;
11777 return 0;
11778 }
Chris Lattner836692d2007-01-15 06:51:56 +000011779
11780 // If the RHS is an alloca with a single use, zapify the store, making the
11781 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011782 // If the RHS is an alloca with a two uses, the other one being a
11783 // llvm.dbg.declare, zapify the store and the declare, making the
11784 // alloca dead. We must do this to prevent declare's from affecting
11785 // codegen.
11786 if (!SI.isVolatile()) {
11787 if (Ptr->hasOneUse()) {
11788 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011789 EraseInstFromFunction(SI);
11790 ++NumCombined;
11791 return 0;
11792 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011793 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11794 if (isa<AllocaInst>(GEP->getOperand(0))) {
11795 if (GEP->getOperand(0)->hasOneUse()) {
11796 EraseInstFromFunction(SI);
11797 ++NumCombined;
11798 return 0;
11799 }
11800 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11801 EraseInstFromFunction(*DI);
11802 EraseInstFromFunction(SI);
11803 ++NumCombined;
11804 return 0;
11805 }
11806 }
11807 }
11808 }
11809 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11810 EraseInstFromFunction(*DI);
11811 EraseInstFromFunction(SI);
11812 ++NumCombined;
11813 return 0;
11814 }
Chris Lattner836692d2007-01-15 06:51:56 +000011815 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011816
Dan Gohman9941f742007-07-20 16:34:21 +000011817 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011818 if (TD) {
11819 unsigned KnownAlign =
11820 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11821 if (KnownAlign >
11822 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11823 SI.getAlignment()))
11824 SI.setAlignment(KnownAlign);
11825 }
Dan Gohman9941f742007-07-20 16:34:21 +000011826
Dale Johannesenacb51a32009-03-03 01:43:03 +000011827 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011828 // stores to the same location, separated by a few arithmetic operations. This
11829 // situation often occurs with bitfield accesses.
11830 BasicBlock::iterator BBI = &SI;
11831 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11832 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011833 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011834 // Don't count debug info directives, lest they affect codegen,
11835 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11836 // It is necessary for correctness to skip those that feed into a
11837 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011838 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011839 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011840 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011841 continue;
11842 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011843
11844 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11845 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011846 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11847 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011848 ++NumDeadStore;
11849 ++BBI;
11850 EraseInstFromFunction(*PrevSI);
11851 continue;
11852 }
11853 break;
11854 }
11855
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011856 // If this is a load, we have to stop. However, if the loaded value is from
11857 // the pointer we're loading and is producing the pointer we're storing,
11858 // then *this* store is dead (X = load P; store X -> P).
11859 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011860 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11861 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011862 EraseInstFromFunction(SI);
11863 ++NumCombined;
11864 return 0;
11865 }
11866 // Otherwise, this is a load from some other location. Stores before it
11867 // may not be dead.
11868 break;
11869 }
11870
Chris Lattner9ca96412006-02-08 03:25:32 +000011871 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011872 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011873 break;
11874 }
11875
11876
11877 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011878
11879 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011880 if (isa<ConstantPointerNull>(Ptr) &&
11881 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011882 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011883 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011884 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011885 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011886 ++NumCombined;
11887 }
11888 return 0; // Do not modify these!
11889 }
11890
11891 // store undef, Ptr -> noop
11892 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011893 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011894 ++NumCombined;
11895 return 0;
11896 }
11897
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011898 // If the pointer destination is a cast, see if we can fold the cast into the
11899 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011900 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011901 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11902 return Res;
11903 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011904 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011905 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11906 return Res;
11907
Chris Lattner408902b2005-09-12 23:23:25 +000011908
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011909 // If this store is the last instruction in the basic block (possibly
11910 // excepting debug info instructions and the pointer bitcasts that feed
11911 // into them), and if the block ends with an unconditional branch, try
11912 // to move it to the successor block.
11913 BBI = &SI;
11914 do {
11915 ++BBI;
11916 } while (isa<DbgInfoIntrinsic>(BBI) ||
11917 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011918 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011919 if (BI->isUnconditional())
11920 if (SimplifyStoreAtEndOfBlock(SI))
11921 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011922
Chris Lattner2f503e62005-01-31 05:36:43 +000011923 return 0;
11924}
11925
Chris Lattner3284d1f2007-04-15 00:07:55 +000011926/// SimplifyStoreAtEndOfBlock - Turn things like:
11927/// if () { *P = v1; } else { *P = v2 }
11928/// into a phi node with a store in the successor.
11929///
Chris Lattner31755a02007-04-15 01:02:18 +000011930/// Simplify things like:
11931/// *P = v1; if () { *P = v2; }
11932/// into a phi node with a store in the successor.
11933///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011934bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11935 BasicBlock *StoreBB = SI.getParent();
11936
11937 // Check to see if the successor block has exactly two incoming edges. If
11938 // so, see if the other predecessor contains a store to the same location.
11939 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011940 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011941
11942 // Determine whether Dest has exactly two predecessors and, if so, compute
11943 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011944 pred_iterator PI = pred_begin(DestBB);
11945 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011946 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011947 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011948 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011949 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011950 return false;
11951
11952 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011953 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011954 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011955 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011956 }
Chris Lattner31755a02007-04-15 01:02:18 +000011957 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011958 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011959
11960 // Bail out if all the relevant blocks aren't distinct (this can happen,
11961 // for example, if SI is in an infinite loop)
11962 if (StoreBB == DestBB || OtherBB == DestBB)
11963 return false;
11964
Chris Lattner31755a02007-04-15 01:02:18 +000011965 // Verify that the other block ends in a branch and is not otherwise empty.
11966 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011967 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011968 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 return false;
11970
Chris Lattner31755a02007-04-15 01:02:18 +000011971 // If the other block ends in an unconditional branch, check for the 'if then
11972 // else' case. there is an instruction before the branch.
11973 StoreInst *OtherStore = 0;
11974 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011975 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011976 // Skip over debugging info.
11977 while (isa<DbgInfoIntrinsic>(BBI) ||
11978 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11979 if (BBI==OtherBB->begin())
11980 return false;
11981 --BBI;
11982 }
11983 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011984 OtherStore = dyn_cast<StoreInst>(BBI);
11985 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11986 return false;
11987 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011988 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011989 // destinations is StoreBB, then we have the if/then case.
11990 if (OtherBr->getSuccessor(0) != StoreBB &&
11991 OtherBr->getSuccessor(1) != StoreBB)
11992 return false;
11993
11994 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011995 // if/then triangle. See if there is a store to the same ptr as SI that
11996 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011997 for (;; --BBI) {
11998 // Check to see if we find the matching store.
11999 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12000 if (OtherStore->getOperand(1) != SI.getOperand(1))
12001 return false;
12002 break;
12003 }
Eli Friedman6903a242008-06-13 22:02:12 +000012004 // If we find something that may be using or overwriting the stored
12005 // value, or if we run out of instructions, we can't do the xform.
12006 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012007 BBI == OtherBB->begin())
12008 return false;
12009 }
12010
12011 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012012 // make sure nothing reads or overwrites the stored value in
12013 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012014 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12015 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012016 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012017 return false;
12018 }
12019 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012020
Chris Lattner31755a02007-04-15 01:02:18 +000012021 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012022 Value *MergedVal = OtherStore->getOperand(0);
12023 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012024 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012025 PN->reserveOperandSpace(2);
12026 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012027 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12028 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012029 }
12030
12031 // Advance to a place where it is safe to insert the new store and
12032 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012033 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012034 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12035 OtherStore->isVolatile()), *BBI);
12036
12037 // Nuke the old stores.
12038 EraseInstFromFunction(SI);
12039 EraseInstFromFunction(*OtherStore);
12040 ++NumCombined;
12041 return true;
12042}
12043
Chris Lattner2f503e62005-01-31 05:36:43 +000012044
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012045Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12046 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012047 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012048 BasicBlock *TrueDest;
12049 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012050 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012051 !isa<Constant>(X)) {
12052 // Swap Destinations and condition...
12053 BI.setCondition(X);
12054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
12056 return &BI;
12057 }
12058
Reid Spencere4d87aa2006-12-23 06:05:41 +000012059 // Cannonicalize fcmp_one -> fcmp_oeq
12060 FCmpInst::Predicate FPred; Value *Y;
12061 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012062 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012063 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12064 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12065 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012066 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012067 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012068 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012069 // Swap Destinations and condition...
12070 BI.setCondition(NewSCC);
12071 BI.setSuccessor(0, FalseDest);
12072 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012073 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012074 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012075 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012076 return &BI;
12077 }
12078
12079 // Cannonicalize icmp_ne -> icmp_eq
12080 ICmpInst::Predicate IPred;
12081 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012082 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012083 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12084 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12085 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12086 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012087 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012088 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012089 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012090 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012091 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012092 BI.setSuccessor(0, FalseDest);
12093 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012094 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012095 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012096 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012097 return &BI;
12098 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012099
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012100 return 0;
12101}
Chris Lattner0864acf2002-11-04 16:18:53 +000012102
Chris Lattner46238a62004-07-03 00:26:11 +000012103Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12104 Value *Cond = SI.getCondition();
12105 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12106 if (I->getOpcode() == Instruction::Add)
12107 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12108 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12109 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012110 SI.setOperand(i,
12111 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012112 AddRHS));
12113 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012114 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012115 return &SI;
12116 }
12117 }
12118 return 0;
12119}
12120
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012121Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012122 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012123
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012124 if (!EV.hasIndices())
12125 return ReplaceInstUsesWith(EV, Agg);
12126
12127 if (Constant *C = dyn_cast<Constant>(Agg)) {
12128 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012129 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012130
12131 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012132 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012133
12134 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12135 // Extract the element indexed by the first index out of the constant
12136 Value *V = C->getOperand(*EV.idx_begin());
12137 if (EV.getNumIndices() > 1)
12138 // Extract the remaining indices out of the constant indexed by the
12139 // first index
12140 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12141 else
12142 return ReplaceInstUsesWith(EV, V);
12143 }
12144 return 0; // Can't handle other constants
12145 }
12146 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12147 // We're extracting from an insertvalue instruction, compare the indices
12148 const unsigned *exti, *exte, *insi, *inse;
12149 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12150 exte = EV.idx_end(), inse = IV->idx_end();
12151 exti != exte && insi != inse;
12152 ++exti, ++insi) {
12153 if (*insi != *exti)
12154 // The insert and extract both reference distinctly different elements.
12155 // This means the extract is not influenced by the insert, and we can
12156 // replace the aggregate operand of the extract with the aggregate
12157 // operand of the insert. i.e., replace
12158 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12159 // %E = extractvalue { i32, { i32 } } %I, 0
12160 // with
12161 // %E = extractvalue { i32, { i32 } } %A, 0
12162 return ExtractValueInst::Create(IV->getAggregateOperand(),
12163 EV.idx_begin(), EV.idx_end());
12164 }
12165 if (exti == exte && insi == inse)
12166 // Both iterators are at the end: Index lists are identical. Replace
12167 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12168 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12169 // with "i32 42"
12170 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12171 if (exti == exte) {
12172 // The extract list is a prefix of the insert list. i.e. replace
12173 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12174 // %E = extractvalue { i32, { i32 } } %I, 1
12175 // with
12176 // %X = extractvalue { i32, { i32 } } %A, 1
12177 // %E = insertvalue { i32 } %X, i32 42, 0
12178 // by switching the order of the insert and extract (though the
12179 // insertvalue should be left in, since it may have other uses).
12180 Value *NewEV = InsertNewInstBefore(
12181 ExtractValueInst::Create(IV->getAggregateOperand(),
12182 EV.idx_begin(), EV.idx_end()),
12183 EV);
12184 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12185 insi, inse);
12186 }
12187 if (insi == inse)
12188 // The insert list is a prefix of the extract list
12189 // We can simply remove the common indices from the extract and make it
12190 // operate on the inserted value instead of the insertvalue result.
12191 // i.e., replace
12192 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12193 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12194 // with
12195 // %E extractvalue { i32 } { i32 42 }, 0
12196 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12197 exti, exte);
12198 }
12199 // Can't simplify extracts from other values. Note that nested extracts are
12200 // already simplified implicitely by the above (extract ( extract (insert) )
12201 // will be translated into extract ( insert ( extract ) ) first and then just
12202 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012203 return 0;
12204}
12205
Chris Lattner220b0cf2006-03-05 00:22:33 +000012206/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12207/// is to leave as a vector operation.
12208static bool CheapToScalarize(Value *V, bool isConstant) {
12209 if (isa<ConstantAggregateZero>(V))
12210 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012211 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012212 if (isConstant) return true;
12213 // If all elts are the same, we can extract.
12214 Constant *Op0 = C->getOperand(0);
12215 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12216 if (C->getOperand(i) != Op0)
12217 return false;
12218 return true;
12219 }
12220 Instruction *I = dyn_cast<Instruction>(V);
12221 if (!I) return false;
12222
12223 // Insert element gets simplified to the inserted element or is deleted if
12224 // this is constant idx extract element and its a constant idx insertelt.
12225 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12226 isa<ConstantInt>(I->getOperand(2)))
12227 return true;
12228 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12229 return true;
12230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12231 if (BO->hasOneUse() &&
12232 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12233 CheapToScalarize(BO->getOperand(1), isConstant)))
12234 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012235 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12236 if (CI->hasOneUse() &&
12237 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12238 CheapToScalarize(CI->getOperand(1), isConstant)))
12239 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012240
12241 return false;
12242}
12243
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012244/// Read and decode a shufflevector mask.
12245///
12246/// It turns undef elements into values that are larger than the number of
12247/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012248static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12249 unsigned NElts = SVI->getType()->getNumElements();
12250 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12251 return std::vector<unsigned>(NElts, 0);
12252 if (isa<UndefValue>(SVI->getOperand(2)))
12253 return std::vector<unsigned>(NElts, 2*NElts);
12254
12255 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012256 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012257 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12258 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012259 Result.push_back(NElts*2); // undef -> 8
12260 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012261 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012262 return Result;
12263}
12264
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012265/// FindScalarElement - Given a vector and an element number, see if the scalar
12266/// value is already around as a register, for example if it were inserted then
12267/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012268static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012269 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012270 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12271 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012272 unsigned Width = PTy->getNumElements();
12273 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012274 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012275
12276 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012277 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012278 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012279 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012280 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012281 return CP->getOperand(EltNo);
12282 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12283 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012284 if (!isa<ConstantInt>(III->getOperand(2)))
12285 return 0;
12286 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012287
12288 // If this is an insert to the element we are looking for, return the
12289 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012290 if (EltNo == IIElt)
12291 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012292
12293 // Otherwise, the insertelement doesn't modify the value, recurse on its
12294 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012295 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012296 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012297 unsigned LHSWidth =
12298 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012299 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012300 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012301 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012302 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012303 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012304 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012305 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012306 }
12307
12308 // Otherwise, we don't know.
12309 return 0;
12310}
12311
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012312Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012313 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012314 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012315 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012316
Dan Gohman07a96762007-07-16 14:29:03 +000012317 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012318 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012319 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012320
Reid Spencer9d6565a2007-02-15 02:26:10 +000012321 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012322 // If vector val is constant with all elements the same, replace EI with
12323 // that element. When the elements are not identical, we cannot replace yet
12324 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012325 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012326 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012327 if (C->getOperand(i) != op0) {
12328 op0 = 0;
12329 break;
12330 }
12331 if (op0)
12332 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012333 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012334
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012335 // If extracting a specified index from the vector, see if we can recursively
12336 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012337 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012338 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012339 unsigned VectorWidth =
12340 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012341
12342 // If this is extracting an invalid index, turn this into undef, to avoid
12343 // crashing the code below.
12344 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012345 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012346
Chris Lattner867b99f2006-10-05 06:55:50 +000012347 // This instruction only demands the single element from the input vector.
12348 // If the input vector has a single use, simplify it based on this use
12349 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012350 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012351 APInt UndefElts(VectorWidth, 0);
12352 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012353 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012354 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012355 EI.setOperand(0, V);
12356 return &EI;
12357 }
12358 }
12359
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012361 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012362
12363 // If the this extractelement is directly using a bitcast from a vector of
12364 // the same number of elements, see if we can find the source element from
12365 // it. In this case, we will end up needing to bitcast the scalars.
12366 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12367 if (const VectorType *VT =
12368 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12369 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012370 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12371 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012372 return new BitCastInst(Elt, EI.getType());
12373 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012374 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012375
Chris Lattner73fa49d2006-05-25 22:53:38 +000012376 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012377 if (I->hasOneUse()) {
12378 // Push extractelement into predecessor operation if legal and
12379 // profitable to do so
12380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012381 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12382 if (CheapToScalarize(BO, isConstantElt)) {
12383 ExtractElementInst *newEI0 =
12384 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12385 EI.getName()+".lhs");
12386 ExtractElementInst *newEI1 =
12387 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12388 EI.getName()+".rhs");
12389 InsertNewInstBefore(newEI0, EI);
12390 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012391 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012392 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012393 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012394 unsigned AS =
12395 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012396 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012397 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012398 GetElementPtrInst *GEP =
12399 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012400 InsertNewInstBefore(GEP, EI);
12401 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012402 }
12403 }
12404 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12405 // Extracting the inserted element?
12406 if (IE->getOperand(2) == EI.getOperand(1))
12407 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12408 // If the inserted and extracted elements are constants, they must not
12409 // be the same value, extract from the pre-inserted value instead.
12410 if (isa<Constant>(IE->getOperand(2)) &&
12411 isa<Constant>(EI.getOperand(1))) {
12412 AddUsesToWorkList(EI);
12413 EI.setOperand(0, IE->getOperand(0));
12414 return &EI;
12415 }
12416 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12417 // If this is extracting an element from a shufflevector, figure out where
12418 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012419 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12420 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012421 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012422 unsigned LHSWidth =
12423 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12424
12425 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012426 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012427 else if (SrcIdx < LHSWidth*2) {
12428 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012429 Src = SVI->getOperand(1);
12430 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012431 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012432 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012433 return new ExtractElementInst(Src,
12434 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012435 }
12436 }
Eli Friedman2451a642009-07-18 23:06:53 +000012437 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012438 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012439 return 0;
12440}
12441
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012442/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12443/// elements from either LHS or RHS, return the shuffle mask and true.
12444/// Otherwise, return false.
12445static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012446 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012447 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012448 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12449 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012450 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012451
12452 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012453 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012454 return true;
12455 } else if (V == LHS) {
12456 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012457 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012458 return true;
12459 } else if (V == RHS) {
12460 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012461 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012462 return true;
12463 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12464 // If this is an insert of an extract from some other vector, include it.
12465 Value *VecOp = IEI->getOperand(0);
12466 Value *ScalarOp = IEI->getOperand(1);
12467 Value *IdxOp = IEI->getOperand(2);
12468
Chris Lattnerd929f062006-04-27 21:14:21 +000012469 if (!isa<ConstantInt>(IdxOp))
12470 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012471 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012472
12473 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12474 // Okay, we can handle this if the vector we are insertinting into is
12475 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012476 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012477 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012478 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012479 return true;
12480 }
12481 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12482 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012483 EI->getOperand(0)->getType() == V->getType()) {
12484 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012485 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012486
12487 // This must be extracting from either LHS or RHS.
12488 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12489 // Okay, we can handle this if the vector we are insertinting into is
12490 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012491 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012492 // If so, update the mask to reflect the inserted value.
12493 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012494 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012495 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012496 } else {
12497 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012498 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012499 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012500
12501 }
12502 return true;
12503 }
12504 }
12505 }
12506 }
12507 }
12508 // TODO: Handle shufflevector here!
12509
12510 return false;
12511}
12512
12513/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12514/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12515/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012516static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012517 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012518 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012519 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012520 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012521 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012522
12523 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012524 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012525 return V;
12526 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012527 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012528 return V;
12529 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530 // If this is an insert of an extract from some other vector, include it.
12531 Value *VecOp = IEI->getOperand(0);
12532 Value *ScalarOp = IEI->getOperand(1);
12533 Value *IdxOp = IEI->getOperand(2);
12534
12535 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12536 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12537 EI->getOperand(0)->getType() == V->getType()) {
12538 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012539 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12540 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012541
12542 // Either the extracted from or inserted into vector must be RHSVec,
12543 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012544 if (EI->getOperand(0) == RHS || RHS == 0) {
12545 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012546 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012547 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012548 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012549 return V;
12550 }
12551
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012552 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012553 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12554 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012555 // Everything but the extracted element is replaced with the RHS.
12556 for (unsigned i = 0; i != NumElts; ++i) {
12557 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012558 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 }
12560 return V;
12561 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012562
12563 // If this insertelement is a chain that comes from exactly these two
12564 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012565 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12566 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012567 return EI->getOperand(0);
12568
Chris Lattnerefb47352006-04-15 01:39:45 +000012569 }
12570 }
12571 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012572 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012573
12574 // Otherwise, can't do anything fancy. Return an identity vector.
12575 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012576 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012577 return V;
12578}
12579
12580Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12581 Value *VecOp = IE.getOperand(0);
12582 Value *ScalarOp = IE.getOperand(1);
12583 Value *IdxOp = IE.getOperand(2);
12584
Chris Lattner599ded12007-04-09 01:11:16 +000012585 // Inserting an undef or into an undefined place, remove this.
12586 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12587 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012588
Chris Lattnerefb47352006-04-15 01:39:45 +000012589 // If the inserted element was extracted from some other vector, and if the
12590 // indexes are constant, try to turn this into a shufflevector operation.
12591 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12592 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12593 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012594 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012595 unsigned ExtractedIdx =
12596 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012598
12599 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12600 return ReplaceInstUsesWith(IE, VecOp);
12601
12602 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012603 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012604
12605 // If we are extracting a value from a vector, then inserting it right
12606 // back into the same place, just use the input vector.
12607 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12608 return ReplaceInstUsesWith(IE, VecOp);
12609
12610 // We could theoretically do this for ANY input. However, doing so could
12611 // turn chains of insertelement instructions into a chain of shufflevector
12612 // instructions, and right now we do not merge shufflevectors. As such,
12613 // only do this in a situation where it is clear that there is benefit.
12614 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12615 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12616 // the values of VecOp, except then one read from EIOp0.
12617 // Build a new shuffle mask.
12618 std::vector<Constant*> Mask;
12619 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012620 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012621 else {
12622 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012623 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012624 NumVectorElts));
12625 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012626 Mask[InsertedIdx] =
12627 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012628 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012629 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012630 }
12631
12632 // If this insertelement isn't used by some other insertelement, turn it
12633 // (and any insertelements it points to), into one big shuffle.
12634 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12635 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012636 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012637 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12638 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012639 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012640 return new ShuffleVectorInst(LHS, RHS,
12641 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012642 }
12643 }
12644 }
12645
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012646 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12647 APInt UndefElts(VWidth, 0);
12648 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12649 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12650 return &IE;
12651
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 return 0;
12653}
12654
12655
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012656Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12657 Value *LHS = SVI.getOperand(0);
12658 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012659 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012660
12661 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012662
Chris Lattner867b99f2006-10-05 06:55:50 +000012663 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012664 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012665 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012666
Dan Gohman488fbfc2008-09-09 18:11:14 +000012667 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012668
12669 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12670 return 0;
12671
Evan Cheng388df622009-02-03 10:05:09 +000012672 APInt UndefElts(VWidth, 0);
12673 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12674 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012675 LHS = SVI.getOperand(0);
12676 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012677 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012678 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012679
Chris Lattner863bcff2006-05-25 23:48:38 +000012680 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12681 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12682 if (LHS == RHS || isa<UndefValue>(LHS)) {
12683 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012684 // shuffle(undef,undef,mask) -> undef.
12685 return ReplaceInstUsesWith(SVI, LHS);
12686 }
12687
Chris Lattner863bcff2006-05-25 23:48:38 +000012688 // Remap any references to RHS to use LHS.
12689 std::vector<Constant*> Elts;
12690 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012691 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012693 else {
12694 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012695 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012696 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012697 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012698 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012699 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012700 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012701 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012702 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012703 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012704 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012705 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12706 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012707 LHS = SVI.getOperand(0);
12708 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012709 MadeChange = true;
12710 }
12711
Chris Lattner7b2e27922006-05-26 00:29:06 +000012712 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012713 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012714
Chris Lattner863bcff2006-05-25 23:48:38 +000012715 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12716 if (Mask[i] >= e*2) continue; // Ignore undef values.
12717 // Is this an identity shuffle of the LHS value?
12718 isLHSID &= (Mask[i] == i);
12719
12720 // Is this an identity shuffle of the RHS value?
12721 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012722 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012723
Chris Lattner863bcff2006-05-25 23:48:38 +000012724 // Eliminate identity shuffles.
12725 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12726 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012727
Chris Lattner7b2e27922006-05-26 00:29:06 +000012728 // If the LHS is a shufflevector itself, see if we can combine it with this
12729 // one without producing an unusual shuffle. Here we are really conservative:
12730 // we are absolutely afraid of producing a shuffle mask not in the input
12731 // program, because the code gen may not be smart enough to turn a merged
12732 // shuffle into two specific shuffles: it may produce worse code. As such,
12733 // we only merge two shuffles if the result is one of the two input shuffle
12734 // masks. In this case, merging the shuffles just removes one instruction,
12735 // which we know is safe. This is good for things like turning:
12736 // (splat(splat)) -> splat.
12737 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12738 if (isa<UndefValue>(RHS)) {
12739 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12740
12741 std::vector<unsigned> NewMask;
12742 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12743 if (Mask[i] >= 2*e)
12744 NewMask.push_back(2*e);
12745 else
12746 NewMask.push_back(LHSMask[Mask[i]]);
12747
12748 // If the result mask is equal to the src shuffle or this shuffle mask, do
12749 // the replacement.
12750 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012751 unsigned LHSInNElts =
12752 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012753 std::vector<Constant*> Elts;
12754 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012755 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012756 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012757 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012758 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012759 }
12760 }
12761 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12762 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012763 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012764 }
12765 }
12766 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012767
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012768 return MadeChange ? &SVI : 0;
12769}
12770
12771
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012772
Chris Lattnerea1c4542004-12-08 23:43:58 +000012773
12774/// TryToSinkInstruction - Try to move the specified instruction from its
12775/// current block into the beginning of DestBlock, which can only happen if it's
12776/// safe to move the instruction past all of the instructions between it and the
12777/// end of its block.
12778static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12779 assert(I->hasOneUse() && "Invariants didn't hold!");
12780
Chris Lattner108e9022005-10-27 17:13:11 +000012781 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012782 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012783 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012784
Chris Lattnerea1c4542004-12-08 23:43:58 +000012785 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012786 if (isa<AllocaInst>(I) && I->getParent() ==
12787 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012788 return false;
12789
Chris Lattner96a52a62004-12-09 07:14:34 +000012790 // We can only sink load instructions if there is nothing between the load and
12791 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012792 if (I->mayReadFromMemory()) {
12793 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012794 Scan != E; ++Scan)
12795 if (Scan->mayWriteToMemory())
12796 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012797 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012798
Dan Gohman02dea8b2008-05-23 21:05:58 +000012799 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012800
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012801 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012802 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012803 ++NumSunkInst;
12804 return true;
12805}
12806
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012807
12808/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12809/// all reachable code to the worklist.
12810///
12811/// This has a couple of tricks to make the code faster and more powerful. In
12812/// particular, we constant fold and DCE instructions as we go, to avoid adding
12813/// them to the worklist (this significantly speeds up instcombine on code where
12814/// many instructions are dead or constant). Additionally, if we find a branch
12815/// whose condition is a known constant, we only visit the reachable successors.
12816///
12817static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012818 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012819 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012820 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012821 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012822 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012823
Chris Lattner2c7718a2007-03-23 19:17:18 +000012824 while (!Worklist.empty()) {
12825 BB = Worklist.back();
12826 Worklist.pop_back();
12827
12828 // We have now visited this block! If we've already been here, ignore it.
12829 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012830
12831 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012832 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12833 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012834
Chris Lattner2c7718a2007-03-23 19:17:18 +000012835 // DCE instruction if trivially dead.
12836 if (isInstructionTriviallyDead(Inst)) {
12837 ++NumDeadInst;
12838 DOUT << "IC: DCE: " << *Inst;
12839 Inst->eraseFromParent();
12840 continue;
12841 }
12842
12843 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012844 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012845 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12846 Inst->replaceAllUsesWith(C);
12847 ++NumConstProp;
12848 Inst->eraseFromParent();
12849 continue;
12850 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012851
Devang Patel7fe1dec2008-11-19 18:56:50 +000012852 // If there are two consecutive llvm.dbg.stoppoint calls then
12853 // it is likely that the optimizer deleted code in between these
12854 // two intrinsics.
12855 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12856 if (DBI_Next) {
12857 if (DBI_Prev
12858 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12859 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12860 IC.RemoveFromWorkList(DBI_Prev);
12861 DBI_Prev->eraseFromParent();
12862 }
12863 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012864 } else {
12865 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012866 }
12867
Chris Lattner2c7718a2007-03-23 19:17:18 +000012868 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012869 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012870
12871 // Recursively visit successors. If this is a branch or switch on a
12872 // constant, only visit the reachable successor.
12873 TerminatorInst *TI = BB->getTerminator();
12874 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12875 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12876 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012877 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012878 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012879 continue;
12880 }
12881 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12882 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12883 // See if this is an explicit destination.
12884 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12885 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012886 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012887 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012888 continue;
12889 }
12890
12891 // Otherwise it is the default destination.
12892 Worklist.push_back(SI->getSuccessor(0));
12893 continue;
12894 }
12895 }
12896
12897 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12898 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012899 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012900}
12901
Chris Lattnerec9c3582007-03-03 02:04:50 +000012902bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012903 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012904 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012905
12906 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12907 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012908
Chris Lattnerb3d59702005-07-07 20:40:38 +000012909 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012910 // Do a depth-first traversal of the function, populate the worklist with
12911 // the reachable instructions. Ignore blocks that are not reachable. Keep
12912 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012913 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012914 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012915
Chris Lattnerb3d59702005-07-07 20:40:38 +000012916 // Do a quick scan over the function. If we find any blocks that are
12917 // unreachable, remove any instructions inside of them. This prevents
12918 // the instcombine code from having to deal with some bad special cases.
12919 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12920 if (!Visited.count(BB)) {
12921 Instruction *Term = BB->getTerminator();
12922 while (Term != BB->begin()) { // Remove instrs bottom-up
12923 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012924
Bill Wendlingb7427032006-11-26 09:46:52 +000012925 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012926 // A debug intrinsic shouldn't force another iteration if we weren't
12927 // going to do one without it.
12928 if (!isa<DbgInfoIntrinsic>(I)) {
12929 ++NumDeadInst;
12930 Changed = true;
12931 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012932 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012933 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012934 I->eraseFromParent();
12935 }
12936 }
12937 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012938
Chris Lattnerdbab3862007-03-02 21:28:56 +000012939 while (!Worklist.empty()) {
12940 Instruction *I = RemoveOneFromWorkList();
12941 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012942
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012943 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012944 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012945 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012946 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012947 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012948 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012949
Bill Wendlingb7427032006-11-26 09:46:52 +000012950 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012951
12952 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012953 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012954 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012955 continue;
12956 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012957
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012958 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012959 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012960 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012961
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012962 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012963 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012964 ReplaceInstUsesWith(*I, C);
12965
Chris Lattner62b14df2002-09-02 04:59:56 +000012966 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012967 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012968 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012969 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012970 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012971 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012972
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012973 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012974 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012975 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12976 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012977 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12978 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012979 if (NewC != CE) {
12980 i->set(NewC);
12981 Changed = true;
12982 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012983 }
12984
Chris Lattnerea1c4542004-12-08 23:43:58 +000012985 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012986 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012987 BasicBlock *BB = I->getParent();
12988 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12989 if (UserParent != BB) {
12990 bool UserIsSuccessor = false;
12991 // See if the user is one of our successors.
12992 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12993 if (*SI == UserParent) {
12994 UserIsSuccessor = true;
12995 break;
12996 }
12997
12998 // If the user is one of our immediate successors, and if that successor
12999 // only has us as a predecessors (we'd have to split the critical edge
13000 // otherwise), we can keep going.
13001 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13002 next(pred_begin(UserParent)) == pred_end(UserParent))
13003 // Okay, the CFG is simple enough, try to sink this instruction.
13004 Changed |= TryToSinkInstruction(I, UserParent);
13005 }
13006 }
13007
Chris Lattner8a2a3112001-12-14 16:52:21 +000013008 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013009#ifndef NDEBUG
13010 std::string OrigI;
13011#endif
13012 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013013 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013014 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013015 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013016 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013017 DOUT << "IC: Old = " << *I
13018 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013019
Chris Lattnerf523d062004-06-09 05:08:07 +000013020 // Everything uses the new instruction now.
13021 I->replaceAllUsesWith(Result);
13022
13023 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013024 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013025 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013026
Chris Lattner6934a042007-02-11 01:23:03 +000013027 // Move the name to the new instruction first.
13028 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013029
13030 // Insert the new instruction into the basic block...
13031 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013032 BasicBlock::iterator InsertPos = I;
13033
13034 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13035 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13036 ++InsertPos;
13037
13038 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013039
Chris Lattner00d51312004-05-01 23:27:23 +000013040 // Make sure that we reprocess all operands now that we reduced their
13041 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013042 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013043
Chris Lattnerf523d062004-06-09 05:08:07 +000013044 // Instructions can end up on the worklist more than once. Make sure
13045 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013046 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013047
13048 // Erase the old instruction.
13049 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013050 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013051#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013052 DOUT << "IC: Mod = " << OrigI
13053 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013054#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013055
Chris Lattner90ac28c2002-08-02 19:29:35 +000013056 // If the instruction was modified, it's possible that it is now dead.
13057 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013058 if (isInstructionTriviallyDead(I)) {
13059 // Make sure we process all operands now that we are reducing their
13060 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013061 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013062
Chris Lattner00d51312004-05-01 23:27:23 +000013063 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013064 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013065 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013066 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013067 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013068 AddToWorkList(I);
13069 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013070 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013071 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013072 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013073 }
13074 }
13075
Chris Lattnerec9c3582007-03-03 02:04:50 +000013076 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013077
13078 // Do an explicit clear, this shrinks the map if needed.
13079 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013080 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013081}
13082
Chris Lattnerec9c3582007-03-03 02:04:50 +000013083
13084bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013085 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013086 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013087
Chris Lattnerec9c3582007-03-03 02:04:50 +000013088 bool EverMadeChange = false;
13089
13090 // Iterate while there is work to do.
13091 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013092 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013093 EverMadeChange = true;
13094 return EverMadeChange;
13095}
13096
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013097FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013098 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013099}