blob: f3fb4fb7f481ffc82cdf3ebbcd03b2dd2cc7d00c [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"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000204
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000208 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000223 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000232 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000233 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000234 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000235 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000236 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000237 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000238 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000245
Chris Lattner9fe38862003-06-19 17:00:31 +0000246 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000247 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000253
Chris Lattner28977af2004-04-05 01:30:19 +0000254 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
Chris Lattner955f3312004-09-28 21:48:02 +0000258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000263 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000264 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000265 }
266
Chris Lattner0c967662004-09-24 15:21:34 +0000267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000272 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000273
Chris Lattnere2ed0572006-04-06 19:19:17 +0000274 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000275 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000276
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000278 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000279 return C;
280 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Chris Lattner0c967662004-09-24 15:21:34 +0000286
Chris Lattner8b170942002-08-09 23:47:40 +0000287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000302 return &I;
303 }
Chris Lattner8b170942002-08-09 23:47:40 +0000304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305
306 // EraseInstFromFunction - When dealing with an instruction that has side
307 // effects or produces a void value, we can't rely on DCE to delete the
308 // instruction. Instead, visit methods should return the value returned by
309 // this function.
310 Instruction *EraseInstFromFunction(Instruction &I) {
311 assert(I.use_empty() && "Cannot erase instruction that is used!");
312 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000314 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 return 0; // Don't do anything with FI
316 }
Chris Lattner173234a2008-06-02 01:18:21 +0000317
318 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319 APInt &KnownOne, unsigned Depth = 0) const {
320 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321 }
322
323 bool MaskedValueIsZero(Value *V, const APInt &Mask,
324 unsigned Depth = 0) const {
325 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326 }
327 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328 return llvm::ComputeNumSignBits(Op, TD, Depth);
329 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000330
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000331 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Chris Lattner886ab6c2009-01-31 08:15:18 +0000341 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342 /// based on the demanded bits.
343 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth);
346 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000347 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000348 unsigned Depth=0);
349
350 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351 /// SimplifyDemandedBits knows about. See if the instruction has any
352 /// properties that allow us to simplify its operands.
353 bool SimplifyDemandedInstructionBits(Instruction &Inst);
354
Evan Cheng388df622009-02-03 10:05:09 +0000355 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
356 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000357
Chris Lattner4e998b22004-09-29 05:07:12 +0000358 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359 // PHI node as operand #0, see if we can fold the instruction into the PHI
360 // (which is only possible if all operands to the PHI are constants).
361 Instruction *FoldOpIntoPhi(Instruction &I);
362
Chris Lattnerbac32862004-11-14 19:13:23 +0000363 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364 // operator and they all are only used by the PHI, PHI together their
365 // inputs, and do the operation once, to the result of the PHI.
366 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000367 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000368 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
Chris Lattner7da52b22006-11-01 04:51:18 +0000370
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000371 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000375 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000376 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000378 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000379 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000380 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000381 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000382 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000383
Chris Lattnerafe91a52006-06-15 19:07:26 +0000384
Reid Spencerc55b2432006-12-13 18:21:21 +0000385 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000386
Dan Gohmaneee962e2008-04-10 18:43:06 +0000387 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000388 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389 unsigned GetOrEnforceKnownAlignment(Value *V,
390 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000391
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392 };
393}
394
Dan Gohman844731a2008-05-13 00:00:25 +0000395char InstCombiner::ID = 0;
396static RegisterPass<InstCombiner>
397X("instcombine", "Combine redundant instructions");
398
Chris Lattner4f98c562003-03-10 21:43:22 +0000399// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000400// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000401static unsigned getComplexity(Value *V) {
402 if (isa<Instruction>(V)) {
403 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000404 return 3;
405 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000406 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 if (isa<Argument>(V)) return 3;
408 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000410
Chris Lattnerc8802d22003-03-11 00:12:48 +0000411// isOnlyUse - Return true if this instruction will be deleted if we stop using
412// it.
413static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000414 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000415}
416
Chris Lattner4cb170c2004-02-23 06:38:22 +0000417// getPromotedType - Return the specified type promoted as it would be to pass
418// though a va_arg area...
419static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000420 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421 if (ITy->getBitWidth() < 32)
422 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000423 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000424 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000425}
426
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000427/// getBitCastOperand - If the specified operand is a CastInst, a constant
428/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000430static Value *getBitCastOperand(Value *V) {
431 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000432 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000433 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435 // GetElementPtrInst?
436 if (GEP->hasAllZeroIndices())
437 return GEP->getOperand(0);
438 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000439 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 else if (CE->getOpcode() == Instruction::GetElementPtr) {
443 // GetElementPtr ConstantExp?
444 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445 I != E; ++I) {
446 ConstantInt *CI = dyn_cast<ConstantInt>(I);
447 if (!CI || !CI->isZero())
448 // Any non-zero indices? Not cast-like.
449 return 0;
450 }
451 // All-zero indices? This is just like casting.
452 return CE->getOperand(0);
453 }
454 }
Chris Lattnereed48272005-09-13 00:40:14 +0000455 return 0;
456}
457
Reid Spencer3da59db2006-11-27 01:05:10 +0000458/// This function is a wrapper around CastInst::isEliminableCastPair. It
459/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000460static Instruction::CastOps
461isEliminableCastPair(
462 const CastInst *CI, ///< The first cast instruction
463 unsigned opcode, ///< The opcode of the second cast instruction
464 const Type *DstTy, ///< The target type for the second cast instruction
465 TargetData *TD ///< The target data for pointer size
466) {
467
468 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
469 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471 // Get the opcodes of the two Cast instructions
472 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000474
Reid Spencer3da59db2006-11-27 01:05:10 +0000475 return Instruction::CastOps(
476 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000478}
479
480/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481/// in any code being generated. It does not require codegen if V is simple
482/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000483static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
484 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000485 if (V->getType() == Ty || isa<Constant>(V)) return false;
486
Chris Lattner01575b72006-05-25 23:24:33 +0000487 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000490 return false;
491 return true;
492}
493
Chris Lattner4f98c562003-03-10 21:43:22 +0000494// SimplifyCommutative - This performs a few simplifications for commutative
495// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000496//
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// 1. Order operands such that they are listed from right (least complex) to
498// left (most complex). This puts constants before unary operators before
499// binary operators.
500//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000501// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000505 bool Changed = false;
506 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000508
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 if (!I.isAssociative()) return Changed;
510 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000514 Constant *Folded = ConstantExpr::get(I.getOpcode(),
515 cast<Constant>(I.getOperand(1)),
516 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 I.setOperand(0, Op->getOperand(0));
518 I.setOperand(1, Folded);
519 return true;
520 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522 isOnlyUse(Op) && isOnlyUse(Op1)) {
523 Constant *C1 = cast<Constant>(Op->getOperand(1));
524 Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000528 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 Op1->getOperand(0),
530 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000531 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 I.setOperand(0, New);
533 I.setOperand(1, Folded);
534 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000535 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000536 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000537 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000538}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000539
Reid Spencere4d87aa2006-12-23 06:05:41 +0000540/// SimplifyCompare - For a CmpInst this function just orders the operands
541/// so that theyare listed from right (least complex) to left (most complex).
542/// This puts constants before unary operators before binary operators.
543bool InstCombiner::SimplifyCompare(CmpInst &I) {
544 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545 return false;
546 I.swapOperands();
547 // Compare instructions are not associative so there's nothing else we can do.
548 return true;
549}
550
Chris Lattner8d969642003-03-10 23:06:50 +0000551// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000553//
Chris Lattner8d969642003-03-10 23:06:50 +0000554static inline Value *dyn_castNegVal(Value *V) {
555 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000556 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000557
Chris Lattner0ce85802004-12-14 20:08:06 +0000558 // Constants can be considered to be negated values if they can be folded.
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000561
562 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563 if (C->getType()->getElementType()->isInteger())
564 return ConstantExpr::getNeg(C);
565
Chris Lattner8d969642003-03-10 23:06:50 +0000566 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569static inline Value *dyn_castNotVal(Value *V) {
570 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000571 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000572
573 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000574 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000575 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
577}
578
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579// dyn_castFoldableMul - If this value is a multiply that can be folded into
580// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000581// non-constant operand of the multiply, and set CST to point to the multiplier.
582// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583//
Chris Lattner50af16a2004-11-13 19:50:12 +0000584static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000585 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000586 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000591 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000593 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000594 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 return I->getOperand(0);
597 }
598 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000600}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000601
Chris Lattner574da9b2005-01-13 20:14:25 +0000602/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603/// expression, return it.
604static User *dyn_castGetElementPtr(Value *V) {
605 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr)
608 return cast<User>(V);
609 return false;
610}
611
Dan Gohmaneee962e2008-04-10 18:43:06 +0000612/// getOpcode - If this is an Instruction or a ConstantExpr, return the
613/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000614static unsigned getOpcode(const Value *V) {
615 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000617 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return CE->getOpcode();
619 // Use UserOp1 to mean there's no opcode.
620 return Instruction::UserOp1;
621}
622
Reid Spencer7177c3a2007-03-25 05:33:51 +0000623/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000624static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000625 APInt Val(C->getValue());
626 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000627}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632}
633/// Add - Add two ConstantInts together
634static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() + C2->getValue());
636}
637/// And - Bitwise AND two ConstantInts together
638static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() & C2->getValue());
640}
641/// Subtract - Subtract one ConstantInt from another
642static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() - C2->getValue());
644}
645/// Multiply - Multiply two ConstantInts together
646static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000648}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 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,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 APInt Demanded) {
679 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();
693 I->setOperand(OpNo, ConstantInt::get(Demanded));
694 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.
701static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000702 const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706 assert(KnownZero.getBitWidth() == BitWidth &&
707 KnownOne.getBitWidth() == BitWidth &&
708 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000710 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
Zhou Sheng4acf1552007-03-28 05:15:57 +0000717 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000718 Min.set(BitWidth-1);
719 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
727static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000728 const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 assert(KnownZero.getBitWidth() == BitWidth &&
733 KnownOne.getBitWidth() == BitWidth &&
734 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737
738 // The minimum value is when the unknown bits are all zeros.
739 Min = KnownOne;
740 // The maximum value is when the unknown bits are all ones.
741 Max = KnownOne|UnknownBits;
742}
Chris Lattner255d8912006-02-11 09:31:47 +0000743
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745/// SimplifyDemandedBits knows about. See if the instruction has any
746/// properties that allow us to simplify its operands.
747bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751
752 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
753 KnownZero, KnownOne, 0);
754 if (V == 0) return false;
755 if (V == &Inst) return true;
756 ReplaceInstUsesWith(Inst, V);
757 return true;
758}
759
760/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761/// specified instruction operand if possible, updating it in place. It returns
762/// true if it made any change and false otherwise.
763bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
764 APInt &KnownZero, APInt &KnownOne,
765 unsigned Depth) {
766 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767 KnownZero, KnownOne, Depth);
768 if (NewVal == 0) return false;
769 U.set(NewVal);
770 return true;
771}
772
773
774/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000776/// that only the bits set in DemandedMask of the result of V are ever used
777/// downstream. Consequently, depending on the mask and V, it may be possible
778/// to replace V with a constant or one of its operands. In such cases, this
779/// function does the replacement and returns true. In all other cases, it
780/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000781/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000782/// to be zero in the expression. These are provided to potentially allow the
783/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784/// the expression. KnownOne and KnownZero always follow the invariant that
785/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786/// the bits in KnownOne and KnownZero may only be accurate for those bits set
787/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000789///
790/// This returns null if it did not change anything and it permits no
791/// simplification. This returns V itself if it did some simplification of V's
792/// operands based on the information about what bits are demanded. This returns
793/// some other non-null value if it found out that V is equal to another value
794/// in the context where the specified bits are demanded, but not for all users.
795Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796 APInt &KnownZero, APInt &KnownOne,
797 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000798 assert(V != 0 && "Null pointer of Value???");
799 assert(Depth <= 6 && "Limit Search Depth");
800 uint32_t BitWidth = DemandedMask.getBitWidth();
801 const IntegerType *VTy = cast<IntegerType>(V->getType());
802 assert(VTy->getBitWidth() == BitWidth &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne \
806 must have same BitWidth");
807 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 }
813
Chris Lattner08d2cc72009-01-31 07:26:06 +0000814 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000815 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
819 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 }
821
Chris Lattner4598c942009-01-31 08:24:16 +0000822 if (Depth == 6) // Limit search depth.
823 return 0;
824
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 if (!I) return 0; // Only analyze instructions.
Chris Lattner4598c942009-01-31 08:24:16 +0000827
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000828 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 // If there are multiple uses of this value and we aren't at the root, then
832 // we can't do any simplifications of the operands, because DemandedMask
833 // only reflects the bits demanded by *one* of the users.
834 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000835 // Despite the fact that we can't simplify this instruction in all User's
836 // context, we can at least compute the knownzero/knownone bits, and we can
837 // do simplifications that apply to *just* the one user if we know that
838 // this instruction has a simpler value in that context.
839 if (I->getOpcode() == Instruction::And) {
840 // If either the LHS or the RHS are Zero, the result is zero.
841 ComputeMaskedBits(I->getOperand(1), DemandedMask,
842 RHSKnownZero, RHSKnownOne, Depth+1);
843 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844 LHSKnownZero, LHSKnownOne, Depth+1);
845
846 // If all of the demanded bits are known 1 on one side, return the other.
847 // These bits cannot contribute to the result of the 'and' in this
848 // context.
849 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
850 (DemandedMask & ~LHSKnownZero))
851 return I->getOperand(0);
852 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
853 (DemandedMask & ~RHSKnownZero))
854 return I->getOperand(1);
855
856 // If all of the demanded bits in the inputs are known zeros, return zero.
857 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858 return Constant::getNullValue(VTy);
859
860 } else if (I->getOpcode() == Instruction::Or) {
861 // We can simplify (X|Y) -> X or Y in the user's context if we know that
862 // only bits from X or Y are demanded.
863
864 // If either the LHS or the RHS are One, the result is One.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known zero on one side, return the
871 // other. These bits cannot contribute to the result of the 'or' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
874 (DemandedMask & ~LHSKnownOne))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
877 (DemandedMask & ~RHSKnownOne))
878 return I->getOperand(1);
879
880 // If all of the potentially set bits on one side are known to be set on
881 // the other side, just use the 'other' side.
882 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
883 (DemandedMask & (~RHSKnownZero)))
884 return I->getOperand(0);
885 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
886 (DemandedMask & (~LHSKnownZero)))
887 return I->getOperand(1);
888 }
889
Chris Lattner4598c942009-01-31 08:24:16 +0000890 // Compute the KnownZero/KnownOne bits to simplify things downstream.
891 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892 return 0;
893 }
894
895 // If this is the root being simplified, allow it to have multiple uses,
896 // just set the DemandedMask to all bits so that we can try to simplify the
897 // operands. This allows visitTruncInst (for example) to simplify the
898 // operand of a trunc without duplicating all the logic below.
899 if (Depth == 0 && !V->hasOneUse())
900 DemandedMask = APInt::getAllOnesValue(BitWidth);
901
Reid Spencer8cb68342007-03-12 17:25:59 +0000902 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000903 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000905 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000906 case Instruction::And:
907 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000908 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909 RHSKnownZero, RHSKnownOne, Depth+1) ||
910 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000911 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 return I;
913 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
914 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000915
916 // If all of the demanded bits are known 1 on one side, return the other.
917 // These bits cannot contribute to the result of the 'and'.
918 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
919 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
922 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000924
925 // If all of the demanded bits in the inputs are known zeros, return zero.
926 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000927 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000928
929 // If the RHS is a constant, see if we can simplify it.
930 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // Output known-1 bits are only known if set in both the LHS & RHS.
934 RHSKnownOne &= LHSKnownOne;
935 // Output known-0 are known to be clear if zero in either the LHS | RHS.
936 RHSKnownZero |= LHSKnownZero;
937 break;
938 case Instruction::Or:
939 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If all of the demanded bits are known zero on one side, return the other.
949 // These bits cannot contribute to the result of the 'or'.
950 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
951 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
954 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the potentially set bits on one side are known to be set on
958 // the other side, just use the 'other' side.
959 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
960 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
963 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965
966 // If the RHS is a constant, see if we can simplify it.
967 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000969
970 // Output known-0 bits are only known if clear in both the LHS & RHS.
971 RHSKnownZero &= LHSKnownZero;
972 // Output known-1 are known to be set if set in either the LHS | RHS.
973 RHSKnownOne |= LHSKnownOne;
974 break;
975 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'xor'.
986 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // Output known-0 bits are known if clear or set in both the LHS & RHS.
992 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
993 (RHSKnownOne & LHSKnownOne);
994 // Output known-1 are known to be set if set in only one of the LHS, RHS.
995 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
996 (RHSKnownOne & LHSKnownZero);
997
998 // If all of the demanded bits are known to be zero on one side or the
999 // other, turn this into an *inclusive* or.
1000 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001003 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 }
1007
1008 // If all of the demanded bits on one side are known, and all of the set
1009 // bits on that side are also known to be set on the other side, turn this
1010 // into an AND, as we know the bits will be cleared.
1011 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1013 // all known
1014 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001017 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 }
1020 }
1021
1022 // If the RHS is a constant, see if we can simplify it.
1023 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
1027 RHSKnownZero = KnownZeroOut;
1028 RHSKnownOne = KnownOneOut;
1029 break;
1030 }
1031 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033 RHSKnownZero, RHSKnownOne, Depth+1) ||
1034 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return I;
1037 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1038 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
1040 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042 ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 // Only known if known in both the LHS and RHS.
1046 RHSKnownOne &= LHSKnownOne;
1047 RHSKnownZero &= LHSKnownZero;
1048 break;
1049 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 DemandedMask.zext(truncBf);
1052 RHSKnownZero.zext(truncBf);
1053 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 DemandedMask.trunc(BitWidth);
1058 RHSKnownZero.trunc(BitWidth);
1059 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001061 break;
1062 }
1063 case Instruction::BitCast:
1064 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return false; // vector->int or fp->int?
1066 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 break;
1071 case Instruction::ZExt: {
1072 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
Zhou Shengd48653a2007-03-29 04:45:55 +00001075 DemandedMask.trunc(SrcBitWidth);
1076 RHSKnownZero.trunc(SrcBitWidth);
1077 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 DemandedMask.zext(BitWidth);
1082 RHSKnownZero.zext(BitWidth);
1083 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 break;
1088 }
1089 case Instruction::SExt: {
1090 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001092
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001094 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001095
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 // If any of the sign extended bits are demanded, we know that the sign
1098 // bit is demanded.
1099 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001100 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001101
Zhou Shengd48653a2007-03-29 04:45:55 +00001102 InputDemandedBits.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 InputDemandedBits.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // If the sign bit of the input is known set or clear, then we know the
1114 // top bits of the result.
1115
1116 // If the input sign bit is known zero, or if the NewBits are not demanded
1117 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 }
1125 break;
1126 }
1127 case Instruction::Add: {
1128 // Figure out what the input bits are. If the top bits of the and result
1129 // are not demanded, then the add doesn't demand them from its input
1130 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
1133 // If there is a constant on the RHS, there are a variety of xformations
1134 // we can do.
1135 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136 // If null, this should be simplified elsewhere. Some of the xforms here
1137 // won't work if the RHS is zero.
1138 if (RHS->isZero())
1139 break;
1140
1141 // If the top bit of the output is demanded, demand everything from the
1142 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
1145 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001149
1150 // If the RHS of the add has bits set that can't affect the input, reduce
1151 // the constant.
1152 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // Avoid excess work.
1156 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157 break;
1158
1159 // Turn it into OR if input bits are zero.
1160 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 }
1166
1167 // We can say something about the output known-zero and known-one bits,
1168 // depending on potential carries from the input constant and the
1169 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1170 // bits set and the RHS constant is 0x01001, then we know we have a known
1171 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172
1173 // To compute this, we first compute the potential carry bits. These are
1174 // the bits which may be modified. I'm not aware of a better way to do
1175 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001177 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // Now that we know which bits have carries, compute the known-1/0 sets.
1180
1181 // Bits are known one if they are known zero in one operand and one in the
1182 // other, and there is no input carry.
1183 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1184 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185
1186 // Bits are known zero if they are known zero in both operands and there
1187 // is no input carry.
1188 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189 } else {
1190 // If the high-bits of this ADD are not demanded, then it does not demand
1191 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 // Right fill the mask of bits for this ADD to demand the most
1194 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001195 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197 LHSKnownZero, LHSKnownOne, Depth+1) ||
1198 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 }
1202 }
1203 break;
1204 }
1205 case Instruction::Sub:
1206 // If the high-bits of this SUB are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this SUB to demand the most
1210 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001211 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001212 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214 LHSKnownZero, LHSKnownOne, Depth+1) ||
1215 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001219 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220 // the known zeros and ones.
1221 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 break;
1223 case Instruction::Shl:
1224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001225 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 return I;
1230 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownZero <<= ShiftAmt;
1232 RHSKnownOne <<= ShiftAmt;
1233 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001234 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001235 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 }
1237 break;
1238 case Instruction::LShr:
1239 // For a logical shift right
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001242
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 return I;
1248 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001251 if (ShiftAmt) {
1252 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001254 RHSKnownZero |= HighBits; // high bits known zero.
1255 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 }
1257 break;
1258 case Instruction::AShr:
1259 // If this is an arithmetic shift right and only the low-bit is set, we can
1260 // always convert this into a logical shr, even if the shift amount is
1261 // variable. The low bit of the shift cannot be an input sign bit unless
1262 // the shift amount is >= the size of the datatype, which is undefined.
1263 if (DemandedMask == 1) {
1264 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001269
1270 // If the sign bit is the only bit demanded by this ashr, then there is no
1271 // need to do it, the shift doesn't change the high bit.
1272 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274
1275 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001276 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001277
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001279 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001280 // If any of the "high bits" are demanded, we should set the sign bit as
1281 // demanded.
1282 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return I;
1287 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292
1293 // Handle the sign bits.
1294 APInt SignBit(APInt::getSignBit(BitWidth));
1295 // Adjust to where it is now in the mask.
1296 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1297
1298 // If the input sign bit is known to be zero, or if none of the top bits
1299 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001300 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 (HighBits & ~DemandedMask) == HighBits) {
1302 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307 RHSKnownOne |= HighBits;
1308 }
1309 }
1310 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001311 case Instruction::SRem:
1312 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001313 APInt RA = Rem->getValue().abs();
1314 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001315 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001317
Nick Lewycky8e394322008-11-02 02:41:50 +00001318 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001319 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001323
1324 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001326
1327 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001328
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001330 }
1331 }
1332 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001333 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001334 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337 KnownZero2, KnownOne2, Depth+1) ||
1338 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001339 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001341
Chris Lattner455e9ab2009-01-21 18:09:24 +00001342 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001343 Leaders = std::max(Leaders,
1344 KnownZero2.countLeadingOnes());
1345 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001348 case Instruction::Call:
1349 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350 switch (II->getIntrinsicID()) {
1351 default: break;
1352 case Intrinsic::bswap: {
1353 // If the only bits demanded come from one byte of the bswap result,
1354 // just shift the input byte into position to eliminate the bswap.
1355 unsigned NLZ = DemandedMask.countLeadingZeros();
1356 unsigned NTZ = DemandedMask.countTrailingZeros();
1357
1358 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1359 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1360 // have 14 leading zeros, round to 8.
1361 NLZ &= ~7;
1362 NTZ &= ~7;
1363 // If we need exactly one byte, we can do this transformation.
1364 if (BitWidth-NLZ-NTZ == 8) {
1365 unsigned ResultBit = NTZ;
1366 unsigned InputBit = BitWidth-NTZ-8;
1367
1368 // Replace this with either a left or right shift to get the byte into
1369 // the right place.
1370 Instruction *NewVal;
1371 if (InputBit > ResultBit)
1372 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373 ConstantInt::get(I->getType(), InputBit-ResultBit));
1374 else
1375 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376 ConstantInt::get(I->getType(), ResultBit-InputBit));
1377 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001379 }
1380
1381 // TODO: Could compute known zero/one bits based on the input.
1382 break;
1383 }
1384 }
1385 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001386 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001387 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001388 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001389
1390 // If the client is only demanding bits that we know, return the known
1391 // constant.
1392 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001393 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 return false;
1395}
1396
Chris Lattner867b99f2006-10-05 06:55:50 +00001397
Mon P Wangaeb06d22008-11-10 04:46:22 +00001398/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001399/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001400/// actually used by the caller. This method analyzes which elements of the
1401/// operand are undef and returns that information in UndefElts.
1402///
1403/// If the information about demanded elements can be used to simplify the
1404/// operation, the operation is simplified, then the resultant value is
1405/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001406Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1407 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001408 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001409 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001410 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001411 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001412
1413 if (isa<UndefValue>(V)) {
1414 // If the entire vector is undefined, just return this info.
1415 UndefElts = EltMask;
1416 return 0;
1417 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1418 UndefElts = EltMask;
1419 return UndefValue::get(V->getType());
1420 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001421
Chris Lattner867b99f2006-10-05 06:55:50 +00001422 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001423 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1424 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001425 Constant *Undef = UndefValue::get(EltTy);
1426
1427 std::vector<Constant*> Elts;
1428 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001429 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001430 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001431 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001432 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1433 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001434 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 } else { // Otherwise, defined.
1436 Elts.push_back(CP->getOperand(i));
1437 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001438
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 return NewCP != CP ? NewCP : 0;
1442 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001443 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001444 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001445
1446 // Check if this is identity. If so, return 0 since we are not simplifying
1447 // anything.
1448 if (DemandedElts == ((1ULL << VWidth) -1))
1449 return 0;
1450
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 Constant *Zero = Constant::getNullValue(EltTy);
1453 Constant *Undef = UndefValue::get(EltTy);
1454 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001455 for (unsigned i = 0; i != VWidth; ++i) {
1456 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1457 Elts.push_back(Elt);
1458 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001460 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 }
1462
Dan Gohman488fbfc2008-09-09 18:11:14 +00001463 // Limit search depth.
1464 if (Depth == 10)
1465 return false;
1466
1467 // If multiple users are using the root value, procede with
1468 // simplification conservatively assuming that all elements
1469 // are needed.
1470 if (!V->hasOneUse()) {
1471 // Quit if we find multiple users of a non-root value though.
1472 // They'll be handled when it's their turn to be visited by
1473 // the main instcombine process.
1474 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 // TODO: Just compute the UndefElts information recursively.
1476 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001477
1478 // Conservatively assume that all elements are needed.
1479 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 }
1481
1482 Instruction *I = dyn_cast<Instruction>(V);
1483 if (!I) return false; // Only analyze instructions.
1484
1485 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001486 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 Value *TmpV;
1488 switch (I->getOpcode()) {
1489 default: break;
1490
1491 case Instruction::InsertElement: {
1492 // If this is a variable index, we don't know which element it overwrites.
1493 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001494 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001495 if (Idx == 0) {
1496 // Note that we can't propagate undef elt info, because we don't know
1497 // which elt is getting updated.
1498 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1499 UndefElts2, Depth+1);
1500 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1501 break;
1502 }
1503
1504 // If this is inserting an element that isn't demanded, remove this
1505 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001506 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001507 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 return AddSoonDeadInstToWorklist(*I, 0);
1509
1510 // Otherwise, the element inserted overwrites whatever was there, so the
1511 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001512 APInt DemandedElts2 = DemandedElts;
1513 DemandedElts2.clear(IdxNo);
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001515 UndefElts, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517
1518 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001519 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001520 break;
1521 }
1522 case Instruction::ShuffleVector: {
1523 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001524 uint64_t LHSVWidth =
1525 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001526 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001527 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001528 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001529 unsigned MaskVal = Shuffle->getMaskValue(i);
1530 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001531 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001532 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001533 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001534 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001535 else
Evan Cheng388df622009-02-03 10:05:09 +00001536 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001537 }
1538 }
1539 }
1540
Nate Begeman7b254672009-02-11 22:36:25 +00001541 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001543 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
Nate Begeman7b254672009-02-11 22:36:25 +00001546 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001547 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1548 UndefElts3, Depth+1);
1549 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1550
1551 bool NewUndefElts = false;
1552 for (unsigned i = 0; i < VWidth; i++) {
1553 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001554 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001555 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001556 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001557 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001558 NewUndefElts = true;
1559 UndefElts.set(i);
1560 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001562 if (UndefElts3[MaskVal - LHSVWidth]) {
1563 NewUndefElts = true;
1564 UndefElts.set(i);
1565 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 }
1567 }
1568
1569 if (NewUndefElts) {
1570 // Add additional discovered undefs.
1571 std::vector<Constant*> Elts;
1572 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001573 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 Elts.push_back(UndefValue::get(Type::Int32Ty));
1575 else
1576 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1577 Shuffle->getMaskValue(i)));
1578 }
1579 I->setOperand(2, ConstantVector::get(Elts));
1580 MadeChange = true;
1581 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001582 break;
1583 }
Chris Lattner69878332007-04-14 22:29:23 +00001584 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001585 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001586 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1587 if (!VTy) break;
1588 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001589 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001590 unsigned Ratio;
1591
1592 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001593 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001594 // elements as are demanded of us.
1595 Ratio = 1;
1596 InputDemandedElts = DemandedElts;
1597 } else if (VWidth > InVWidth) {
1598 // Untested so far.
1599 break;
1600
1601 // If there are more elements in the result than there are in the source,
1602 // then an input element is live if any of the corresponding output
1603 // elements are live.
1604 Ratio = VWidth/InVWidth;
1605 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001606 if (DemandedElts[OutIdx])
1607 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001608 }
1609 } else {
1610 // Untested so far.
1611 break;
1612
1613 // If there are more elements in the source than there are in the result,
1614 // then an input element is live if the corresponding output element is
1615 // live.
1616 Ratio = InVWidth/VWidth;
1617 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001618 if (DemandedElts[InIdx/Ratio])
1619 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001620 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001621
Chris Lattner69878332007-04-14 22:29:23 +00001622 // div/rem demand all inputs, because they don't want divide by zero.
1623 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1624 UndefElts2, Depth+1);
1625 if (TmpV) {
1626 I->setOperand(0, TmpV);
1627 MadeChange = true;
1628 }
1629
1630 UndefElts = UndefElts2;
1631 if (VWidth > InVWidth) {
1632 assert(0 && "Unimp");
1633 // If there are more elements in the result than there are in the source,
1634 // then an output element is undef if the corresponding input element is
1635 // undef.
1636 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001637 if (UndefElts2[OutIdx/Ratio])
1638 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001639 } else if (VWidth < InVWidth) {
1640 assert(0 && "Unimp");
1641 // If there are more elements in the source than there are in the result,
1642 // then a result element is undef if all of the corresponding input
1643 // elements are undef.
1644 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001646 if (!UndefElts2[InIdx]) // Not undef?
1647 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001648 }
1649 break;
1650 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001651 case Instruction::And:
1652 case Instruction::Or:
1653 case Instruction::Xor:
1654 case Instruction::Add:
1655 case Instruction::Sub:
1656 case Instruction::Mul:
1657 // div/rem demand all inputs, because they don't want divide by zero.
1658 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1659 UndefElts, Depth+1);
1660 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1661 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1662 UndefElts2, Depth+1);
1663 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1664
1665 // Output elements are undefined if both are undefined. Consider things
1666 // like undef&0. The result is known zero, not undef.
1667 UndefElts &= UndefElts2;
1668 break;
1669
1670 case Instruction::Call: {
1671 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1672 if (!II) break;
1673 switch (II->getIntrinsicID()) {
1674 default: break;
1675
1676 // Binary vector operations that work column-wise. A dest element is a
1677 // function of the corresponding input elements from the two inputs.
1678 case Intrinsic::x86_sse_sub_ss:
1679 case Intrinsic::x86_sse_mul_ss:
1680 case Intrinsic::x86_sse_min_ss:
1681 case Intrinsic::x86_sse_max_ss:
1682 case Intrinsic::x86_sse2_sub_sd:
1683 case Intrinsic::x86_sse2_mul_sd:
1684 case Intrinsic::x86_sse2_min_sd:
1685 case Intrinsic::x86_sse2_max_sd:
1686 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1692
1693 // If only the low elt is demanded and this is a scalarizable intrinsic,
1694 // scalarize it now.
1695 if (DemandedElts == 1) {
1696 switch (II->getIntrinsicID()) {
1697 default: break;
1698 case Intrinsic::x86_sse_sub_ss:
1699 case Intrinsic::x86_sse_mul_ss:
1700 case Intrinsic::x86_sse2_sub_sd:
1701 case Intrinsic::x86_sse2_mul_sd:
1702 // TODO: Lower MIN/MAX/ABS/etc
1703 Value *LHS = II->getOperand(1);
1704 Value *RHS = II->getOperand(2);
1705 // Extract the element as scalars.
1706 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1707 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1708
1709 switch (II->getIntrinsicID()) {
1710 default: assert(0 && "Case stmts out of sync!");
1711 case Intrinsic::x86_sse_sub_ss:
1712 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001713 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001714 II->getName()), *II);
1715 break;
1716 case Intrinsic::x86_sse_mul_ss:
1717 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001718 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001719 II->getName()), *II);
1720 break;
1721 }
1722
1723 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001724 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1725 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001726 InsertNewInstBefore(New, *II);
1727 AddSoonDeadInstToWorklist(*II, 0);
1728 return New;
1729 }
1730 }
1731
1732 // Output elements are undefined if both are undefined. Consider things
1733 // like undef&0. The result is known zero, not undef.
1734 UndefElts &= UndefElts2;
1735 break;
1736 }
1737 break;
1738 }
1739 }
1740 return MadeChange ? I : 0;
1741}
1742
Dan Gohman45b4e482008-05-19 22:14:15 +00001743
Chris Lattner564a7272003-08-13 19:01:45 +00001744/// AssociativeOpt - Perform an optimization on an associative operator. This
1745/// function is designed to check a chain of associative operators for a
1746/// potential to apply a certain optimization. Since the optimization may be
1747/// applicable if the expression was reassociated, this checks the chain, then
1748/// reassociates the expression as necessary to expose the optimization
1749/// opportunity. This makes use of a special Functor, which must define
1750/// 'shouldApply' and 'apply' methods.
1751///
1752template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001753static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001754 unsigned Opcode = Root.getOpcode();
1755 Value *LHS = Root.getOperand(0);
1756
1757 // Quick check, see if the immediate LHS matches...
1758 if (F.shouldApply(LHS))
1759 return F.apply(Root);
1760
1761 // Otherwise, if the LHS is not of the same opcode as the root, return.
1762 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001763 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001764 // Should we apply this transform to the RHS?
1765 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1766
1767 // If not to the RHS, check to see if we should apply to the LHS...
1768 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1769 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1770 ShouldApply = true;
1771 }
1772
1773 // If the functor wants to apply the optimization to the RHS of LHSI,
1774 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1775 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001776 // Now all of the instructions are in the current basic block, go ahead
1777 // and perform the reassociation.
1778 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1779
1780 // First move the selected RHS to the LHS of the root...
1781 Root.setOperand(0, LHSI->getOperand(1));
1782
1783 // Make what used to be the LHS of the root be the user of the root...
1784 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001785 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001786 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1787 return 0;
1788 }
Chris Lattner65725312004-04-16 18:08:07 +00001789 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001790 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001791 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001792 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001793 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001794
1795 // Now propagate the ExtraOperand down the chain of instructions until we
1796 // get to LHSI.
1797 while (TmpLHSI != LHSI) {
1798 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001799 // Move the instruction to immediately before the chain we are
1800 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001801 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001802 ARI = NextLHSI;
1803
Chris Lattner564a7272003-08-13 19:01:45 +00001804 Value *NextOp = NextLHSI->getOperand(1);
1805 NextLHSI->setOperand(1, ExtraOperand);
1806 TmpLHSI = NextLHSI;
1807 ExtraOperand = NextOp;
1808 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001809
Chris Lattner564a7272003-08-13 19:01:45 +00001810 // Now that the instructions are reassociated, have the functor perform
1811 // the transformation...
1812 return F.apply(Root);
1813 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001814
Chris Lattner564a7272003-08-13 19:01:45 +00001815 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1816 }
1817 return 0;
1818}
1819
Dan Gohman844731a2008-05-13 00:00:25 +00001820namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001821
Nick Lewycky02d639f2008-05-23 04:34:58 +00001822// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001823struct AddRHS {
1824 Value *RHS;
1825 AddRHS(Value *rhs) : RHS(rhs) {}
1826 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1827 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001828 return BinaryOperator::CreateShl(Add.getOperand(0),
1829 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001830 }
1831};
1832
1833// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1834// iff C1&C2 == 0
1835struct AddMaskingAnd {
1836 Constant *C2;
1837 AddMaskingAnd(Constant *c) : C2(c) {}
1838 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001839 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001840 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001841 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001842 }
1843 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001844 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001845 }
1846};
1847
Dan Gohman844731a2008-05-13 00:00:25 +00001848}
1849
Chris Lattner6e7ba452005-01-01 16:22:27 +00001850static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001851 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001852 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001853 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001854 }
1855
Chris Lattner2eefe512004-04-09 19:05:30 +00001856 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001857 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1858 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001859
Chris Lattner2eefe512004-04-09 19:05:30 +00001860 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1861 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001862 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1863 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001864 }
1865
1866 Value *Op0 = SO, *Op1 = ConstOperand;
1867 if (!ConstIsRHS)
1868 std::swap(Op0, Op1);
1869 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001871 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001872 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001873 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001874 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001875 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001876 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001877 abort();
1878 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001879 return IC->InsertNewInstBefore(New, I);
1880}
1881
1882// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1883// constant as the other operand, try to fold the binary operator into the
1884// select arguments. This also works for Cast instructions, which obviously do
1885// not have a second operand.
1886static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1887 InstCombiner *IC) {
1888 // Don't modify shared select instructions
1889 if (!SI->hasOneUse()) return 0;
1890 Value *TV = SI->getOperand(1);
1891 Value *FV = SI->getOperand(2);
1892
1893 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001894 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001895 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001896
Chris Lattner6e7ba452005-01-01 16:22:27 +00001897 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1898 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1899
Gabor Greif051a9502008-04-06 20:25:17 +00001900 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1901 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001902 }
1903 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001904}
1905
Chris Lattner4e998b22004-09-29 05:07:12 +00001906
1907/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1908/// node as operand #0, see if we can fold the instruction into the PHI (which
1909/// is only possible if all operands to the PHI are constants).
1910Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1911 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001912 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001913 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001914
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001915 // Check to see if all of the operands of the PHI are constants. If there is
1916 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001917 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001918 BasicBlock *NonConstBB = 0;
1919 for (unsigned i = 0; i != NumPHIValues; ++i)
1920 if (!isa<Constant>(PN->getIncomingValue(i))) {
1921 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001922 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001923 NonConstBB = PN->getIncomingBlock(i);
1924
1925 // If the incoming non-constant value is in I's block, we have an infinite
1926 // loop.
1927 if (NonConstBB == I.getParent())
1928 return 0;
1929 }
1930
1931 // If there is exactly one non-constant value, we can insert a copy of the
1932 // operation in that block. However, if this is a critical edge, we would be
1933 // inserting the computation one some other paths (e.g. inside a loop). Only
1934 // do this if the pred block is unconditionally branching into the phi block.
1935 if (NonConstBB) {
1936 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1937 if (!BI || !BI->isUnconditional()) return 0;
1938 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001939
1940 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001941 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001942 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001943 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001944 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001945
1946 // Next, add all of the operands to the PHI.
1947 if (I.getNumOperands() == 2) {
1948 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001949 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001950 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001952 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1953 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1954 else
1955 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 } else {
1957 assert(PN->getIncomingBlock(i) == NonConstBB);
1958 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001959 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001960 PN->getIncomingValue(i), C, "phitmp",
1961 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001962 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001963 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001964 CI->getPredicate(),
1965 PN->getIncomingValue(i), C, "phitmp",
1966 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001967 else
1968 assert(0 && "Unknown binop!");
1969
Chris Lattnerdbab3862007-03-02 21:28:56 +00001970 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001971 }
1972 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001973 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001974 } else {
1975 CastInst *CI = cast<CastInst>(&I);
1976 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001977 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001978 Value *InV;
1979 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001980 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001981 } else {
1982 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001983 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001984 I.getType(), "phitmp",
1985 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001986 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001987 }
1988 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001989 }
1990 }
1991 return ReplaceInstUsesWith(I, NewPN);
1992}
1993
Chris Lattner2454a2e2008-01-29 06:52:45 +00001994
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001995/// WillNotOverflowSignedAdd - Return true if we can prove that:
1996/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1997/// This basically requires proving that the add in the original type would not
1998/// overflow to change the sign bit or have a carry out.
1999bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2000 // There are different heuristics we can use for this. Here are some simple
2001 // ones.
2002
2003 // Add has the property that adding any two 2's complement numbers can only
2004 // have one carry bit which can change a sign. As such, if LHS and RHS each
2005 // have at least two sign bits, we know that the addition of the two values will
2006 // sign extend fine.
2007 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2008 return true;
2009
2010
2011 // If one of the operands only has one non-zero bit, and if the other operand
2012 // has a known-zero bit in a more significant place than it (not including the
2013 // sign bit) the ripple may go up to and fill the zero, but won't change the
2014 // sign. For example, (X & ~4) + 1.
2015
2016 // TODO: Implement.
2017
2018 return false;
2019}
2020
Chris Lattner2454a2e2008-01-29 06:52:45 +00002021
Chris Lattner7e708292002-06-25 16:13:24 +00002022Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002023 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002024 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002025
Chris Lattner66331a42004-04-10 22:01:55 +00002026 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002027 // X + undef -> undef
2028 if (isa<UndefValue>(RHS))
2029 return ReplaceInstUsesWith(I, RHS);
2030
Chris Lattner66331a42004-04-10 22:01:55 +00002031 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002032 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002033 if (RHSC->isNullValue())
2034 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002035 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002036 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2037 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002038 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002039 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002040
Chris Lattner66331a42004-04-10 22:01:55 +00002041 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002042 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002043 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002044 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002045 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002046 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002047
2048 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2049 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002050 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2051 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002052
2053 // zext(i1) - 1 -> select i1, 0, -1
2054 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2055 if (CI->isAllOnesValue() &&
2056 ZI->getOperand(0)->getType() == Type::Int1Ty)
2057 return SelectInst::Create(ZI->getOperand(0),
2058 Constant::getNullValue(I.getType()),
2059 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002060 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002061
2062 if (isa<PHINode>(LHS))
2063 if (Instruction *NV = FoldOpIntoPhi(I))
2064 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002065
Chris Lattner4f637d42006-01-06 17:59:59 +00002066 ConstantInt *XorRHS = 0;
2067 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002068 if (isa<ConstantInt>(RHSC) &&
2069 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002070 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002071 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002072
Zhou Sheng4351c642007-04-02 08:20:41 +00002073 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002074 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2075 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002076 do {
2077 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002078 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2079 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002080 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2081 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002082 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002083 if (!MaskedValueIsZero(XorLHS,
2084 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002085 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002086 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002087 }
2088 }
2089 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002090 C0080Val = APIntOps::lshr(C0080Val, Size);
2091 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2092 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002093
Reid Spencer35c38852007-03-28 01:36:16 +00002094 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002095 // with funny bit widths then this switch statement should be removed. It
2096 // is just here to get the size of the "middle" type back up to something
2097 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002098 const Type *MiddleType = 0;
2099 switch (Size) {
2100 default: break;
2101 case 32: MiddleType = Type::Int32Ty; break;
2102 case 16: MiddleType = Type::Int16Ty; break;
2103 case 8: MiddleType = Type::Int8Ty; break;
2104 }
2105 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002106 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002107 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002108 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002109 }
2110 }
Chris Lattner66331a42004-04-10 22:01:55 +00002111 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002112
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002113 if (I.getType() == Type::Int1Ty)
2114 return BinaryOperator::CreateXor(LHS, RHS);
2115
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002116 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002117 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002118 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002119
2120 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2121 if (RHSI->getOpcode() == Instruction::Sub)
2122 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2123 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2124 }
2125 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2126 if (LHSI->getOpcode() == Instruction::Sub)
2127 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2128 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2129 }
Robert Bocchino71698282004-07-27 21:02:21 +00002130 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002131
Chris Lattner5c4afb92002-05-08 22:46:53 +00002132 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002133 // -A + -B --> -(A + B)
2134 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002135 if (LHS->getType()->isIntOrIntVector()) {
2136 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002137 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002138 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002139 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002140 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002141 }
2142
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002143 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002144 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002145
2146 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002147 if (!isa<Constant>(RHS))
2148 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002149 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002150
Misha Brukmanfd939082005-04-21 23:48:37 +00002151
Chris Lattner50af16a2004-11-13 19:50:12 +00002152 ConstantInt *C2;
2153 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2154 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002155 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002156
2157 // X*C1 + X*C2 --> X * (C1+C2)
2158 ConstantInt *C1;
2159 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002160 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002161 }
2162
2163 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002164 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002166
Chris Lattnere617c9e2007-01-05 02:17:46 +00002167 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002168 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2169 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002170
Chris Lattnerad3448c2003-02-18 19:57:07 +00002171
Chris Lattner564a7272003-08-13 19:01:45 +00002172 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002173 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002174 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2175 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002176
2177 // A+B --> A|B iff A and B have no bits set in common.
2178 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2179 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2180 APInt LHSKnownOne(IT->getBitWidth(), 0);
2181 APInt LHSKnownZero(IT->getBitWidth(), 0);
2182 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2183 if (LHSKnownZero != 0) {
2184 APInt RHSKnownOne(IT->getBitWidth(), 0);
2185 APInt RHSKnownZero(IT->getBitWidth(), 0);
2186 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2187
2188 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002189 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002190 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002191 }
2192 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002193
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002194 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002195 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002196 Value *W, *X, *Y, *Z;
2197 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2198 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2199 if (W != Y) {
2200 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002201 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002202 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002203 std::swap(W, X);
2204 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002205 std::swap(Y, Z);
2206 std::swap(W, X);
2207 }
2208 }
2209
2210 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002211 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002212 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002213 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002214 }
2215 }
2216 }
2217
Chris Lattner6b032052003-10-02 15:11:26 +00002218 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002219 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002220 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002221 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002222
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002223 // (X & FF00) + xx00 -> (X+xx00) & FF00
2224 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002225 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002226 if (Anded == CRHS) {
2227 // See if all bits from the first bit set in the Add RHS up are included
2228 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002229 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002230
2231 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002232 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002233
2234 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002235 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002236
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002237 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2238 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002239 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002240 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002241 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002242 }
2243 }
2244 }
2245
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002246 // Try to fold constant add into select arguments.
2247 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002248 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002249 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002250 }
2251
Reid Spencer1628cec2006-10-26 06:15:43 +00002252 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002253 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002254 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002255 CastInst *CI = dyn_cast<CastInst>(LHS);
2256 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002257 if (!CI) {
2258 CI = dyn_cast<CastInst>(RHS);
2259 Other = LHS;
2260 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002261 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002262 (CI->getType()->getPrimitiveSizeInBits() ==
2263 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002264 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002265 unsigned AS =
2266 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002267 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2268 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002269 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002270 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002271 }
2272 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002273
Chris Lattner42790482007-12-20 01:56:58 +00002274 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275 {
2276 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002277 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002278 if (!SI) {
2279 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002280 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002281 }
Chris Lattner42790482007-12-20 01:56:58 +00002282 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 Value *TV = SI->getTrueValue();
2284 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002286
2287 // Can we fold the add into the argument of the select?
2288 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2290 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002291 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002292 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2293 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002294 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295 }
2296 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002297
2298 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2299 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2300 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2301 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002302
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002303 // Check for (add (sext x), y), see if we can merge this into an
2304 // integer add followed by a sext.
2305 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2306 // (add (sext x), cst) --> (sext (add x, cst'))
2307 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2308 Constant *CI =
2309 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2310 if (LHSConv->hasOneUse() &&
2311 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2312 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2313 // Insert the new, smaller add.
2314 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2315 CI, "addconv");
2316 InsertNewInstBefore(NewAdd, I);
2317 return new SExtInst(NewAdd, I.getType());
2318 }
2319 }
2320
2321 // (add (sext x), (sext y)) --> (sext (add int x, y))
2322 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2323 // Only do this if x/y have the same type, if at last one of them has a
2324 // single use (so we don't increase the number of sexts), and if the
2325 // integer add will not overflow.
2326 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2327 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2328 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2329 RHSConv->getOperand(0))) {
2330 // Insert the new integer add.
2331 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2332 RHSConv->getOperand(0),
2333 "addconv");
2334 InsertNewInstBefore(NewAdd, I);
2335 return new SExtInst(NewAdd, I.getType());
2336 }
2337 }
2338 }
2339
2340 // Check for (add double (sitofp x), y), see if we can merge this into an
2341 // integer add followed by a promotion.
2342 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2343 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2344 // ... if the constant fits in the integer value. This is useful for things
2345 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2346 // requires a constant pool load, and generally allows the add to be better
2347 // instcombined.
2348 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2349 Constant *CI =
2350 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2351 if (LHSConv->hasOneUse() &&
2352 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2353 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354 // Insert the new integer add.
2355 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2356 CI, "addconv");
2357 InsertNewInstBefore(NewAdd, I);
2358 return new SIToFPInst(NewAdd, I.getType());
2359 }
2360 }
2361
2362 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2363 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2364 // Only do this if x/y have the same type, if at last one of them has a
2365 // single use (so we don't increase the number of int->fp conversions),
2366 // and if the integer add will not overflow.
2367 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2368 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2369 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2370 RHSConv->getOperand(0))) {
2371 // Insert the new integer add.
2372 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2373 RHSConv->getOperand(0),
2374 "addconv");
2375 InsertNewInstBefore(NewAdd, I);
2376 return new SIToFPInst(NewAdd, I.getType());
2377 }
2378 }
2379 }
2380
Chris Lattner7e708292002-06-25 16:13:24 +00002381 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002382}
2383
Chris Lattner7e708292002-06-25 16:13:24 +00002384Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002385 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002386
Chris Lattnerd137ab42008-07-17 06:07:20 +00002387 if (Op0 == Op1 && // sub X, X -> 0
2388 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002389 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002390
Chris Lattner233f7dc2002-08-12 21:17:25 +00002391 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002392 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002393 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002394
Chris Lattnere87597f2004-10-16 18:11:37 +00002395 if (isa<UndefValue>(Op0))
2396 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2397 if (isa<UndefValue>(Op1))
2398 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2399
Chris Lattnerd65460f2003-11-05 01:06:05 +00002400 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2401 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002402 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002403 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002404
Chris Lattnerd65460f2003-11-05 01:06:05 +00002405 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002406 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002407 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002408 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002409
Chris Lattner76b7a062007-01-15 07:02:54 +00002410 // -(X >>u 31) -> (X >>s 31)
2411 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002412 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002413 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002414 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002415 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002416 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002417 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002418 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002419 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002420 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002421 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002422 }
2423 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002424 }
2425 else if (SI->getOpcode() == Instruction::AShr) {
2426 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2427 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002428 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002429 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002430 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002431 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002432 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002433 }
2434 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002435 }
2436 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002437 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002438
2439 // Try to fold constant sub into select arguments.
2440 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002441 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002442 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002443 }
2444
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002445 if (I.getType() == Type::Int1Ty)
2446 return BinaryOperator::CreateXor(Op0, Op1);
2447
Chris Lattner43d84d62005-04-07 16:15:25 +00002448 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2449 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002450 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002451 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002452 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002453 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002455 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2456 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2457 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002459 Op1I->getOperand(0));
2460 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002461 }
2462
Chris Lattnerfd059242003-10-15 16:48:29 +00002463 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002464 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2465 // is not used by anyone else...
2466 //
Chris Lattner0517e722004-02-02 20:09:56 +00002467 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002468 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002469 // Swap the two operands of the subexpr...
2470 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2471 Op1I->setOperand(0, IIOp1);
2472 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002473
Chris Lattnera2881962003-02-18 19:28:33 +00002474 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002476 }
2477
2478 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2479 //
2480 if (Op1I->getOpcode() == Instruction::And &&
2481 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2482 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2483
Chris Lattnerf523d062004-06-09 05:08:07 +00002484 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2486 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002487 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002488
Reid Spencerac5209e2006-10-16 23:08:08 +00002489 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002490 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002491 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002492 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002493 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002494 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002495 ConstantExpr::getNeg(DivRHS));
2496
Chris Lattnerad3448c2003-02-18 19:57:07 +00002497 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002498 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002499 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002500 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002501 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002502 }
Chris Lattner40371712002-05-09 01:29:19 +00002503 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002504 }
Chris Lattnera2881962003-02-18 19:28:33 +00002505
Chris Lattner9919e3d2006-12-02 00:13:08 +00002506 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002507 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002508 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002509 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2510 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2511 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2512 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002513 } else if (Op0I->getOpcode() == Instruction::Sub) {
2514 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002515 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002516 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002517 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002518
Chris Lattner50af16a2004-11-13 19:50:12 +00002519 ConstantInt *C1;
2520 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002521 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002523
Chris Lattner50af16a2004-11-13 19:50:12 +00002524 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2525 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002527 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002528 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002529}
2530
Chris Lattnera0141b92007-07-15 20:42:37 +00002531/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2532/// comparison only checks the sign bit. If it only checks the sign bit, set
2533/// TrueIfSigned if the result of the comparison is true when the input value is
2534/// signed.
2535static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2536 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002537 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002538 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2539 TrueIfSigned = true;
2540 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002541 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2542 TrueIfSigned = true;
2543 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002544 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2545 TrueIfSigned = false;
2546 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002547 case ICmpInst::ICMP_UGT:
2548 // True if LHS u> RHS and RHS == high-bit-mask - 1
2549 TrueIfSigned = true;
2550 return RHS->getValue() ==
2551 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2552 case ICmpInst::ICMP_UGE:
2553 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2554 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002555 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002556 default:
2557 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002558 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002559}
2560
Chris Lattner7e708292002-06-25 16:13:24 +00002561Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002562 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002563 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002564
Chris Lattnere87597f2004-10-16 18:11:37 +00002565 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2567
Chris Lattner233f7dc2002-08-12 21:17:25 +00002568 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002569 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2570 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002571
2572 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002573 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002574 if (SI->getOpcode() == Instruction::Shl)
2575 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002577 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002578
Zhou Sheng843f07672007-04-19 05:39:12 +00002579 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002580 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2581 if (CI->equalsInt(1)) // X * 1 == X
2582 return ReplaceInstUsesWith(I, Op0);
2583 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002584 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002585
Zhou Sheng97b52c22007-03-29 01:57:21 +00002586 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002587 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002588 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002589 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002590 }
Robert Bocchino71698282004-07-27 21:02:21 +00002591 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002592 if (Op1F->isNullValue())
2593 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002594
Chris Lattnera2881962003-02-18 19:28:33 +00002595 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2596 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002597 if (Op1F->isExactlyValue(1.0))
2598 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2599 } else if (isa<VectorType>(Op1->getType())) {
2600 if (isa<ConstantAggregateZero>(Op1))
2601 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002602
2603 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2604 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2605 return BinaryOperator::CreateNeg(Op0, I.getName());
2606
2607 // As above, vector X*splat(1.0) -> X in all defined cases.
2608 if (Constant *Splat = Op1V->getSplatValue()) {
2609 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2610 if (F->isExactlyValue(1.0))
2611 return ReplaceInstUsesWith(I, Op0);
2612 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2613 if (CI->equalsInt(1))
2614 return ReplaceInstUsesWith(I, Op0);
2615 }
2616 }
Chris Lattnera2881962003-02-18 19:28:33 +00002617 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002618
2619 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2620 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002621 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002622 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002623 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002624 Op1, "tmp");
2625 InsertNewInstBefore(Add, I);
2626 Value *C1C2 = ConstantExpr::getMul(Op1,
2627 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002628 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002629
2630 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002631
2632 // Try to fold constant mul into select arguments.
2633 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002634 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002635 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002636
2637 if (isa<PHINode>(Op0))
2638 if (Instruction *NV = FoldOpIntoPhi(I))
2639 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002640 }
2641
Chris Lattnera4f445b2003-03-10 23:23:04 +00002642 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2643 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002644 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002645
Nick Lewycky0c730792008-11-21 07:33:58 +00002646 // (X / Y) * Y = X - (X % Y)
2647 // (X / Y) * -Y = (X % Y) - X
2648 {
2649 Value *Op1 = I.getOperand(1);
2650 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2651 if (!BO ||
2652 (BO->getOpcode() != Instruction::UDiv &&
2653 BO->getOpcode() != Instruction::SDiv)) {
2654 Op1 = Op0;
2655 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2656 }
2657 Value *Neg = dyn_castNegVal(Op1);
2658 if (BO && BO->hasOneUse() &&
2659 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2660 (BO->getOpcode() == Instruction::UDiv ||
2661 BO->getOpcode() == Instruction::SDiv)) {
2662 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2663
2664 Instruction *Rem;
2665 if (BO->getOpcode() == Instruction::UDiv)
2666 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2667 else
2668 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2669
2670 InsertNewInstBefore(Rem, I);
2671 Rem->takeName(BO);
2672
2673 if (Op1BO == Op1)
2674 return BinaryOperator::CreateSub(Op0BO, Rem);
2675 else
2676 return BinaryOperator::CreateSub(Rem, Op0BO);
2677 }
2678 }
2679
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002680 if (I.getType() == Type::Int1Ty)
2681 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2682
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002683 // If one of the operands of the multiply is a cast from a boolean value, then
2684 // we know the bool is either zero or one, so this is a 'masking' multiply.
2685 // See if we can simplify things based on how the boolean was originally
2686 // formed.
2687 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002688 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002689 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002690 BoolCast = CI;
2691 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002692 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002693 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002694 BoolCast = CI;
2695 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002696 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002697 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2698 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002699 bool TIS = false;
2700
Reid Spencere4d87aa2006-12-23 06:05:41 +00002701 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002702 // multiply into a shift/and combination.
2703 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002704 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2705 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002706 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002707 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002708 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002709 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002710 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002711 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002712 BoolCast->getOperand(0)->getName()+
2713 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002714
2715 // If the multiply type is not the same as the source type, sign extend
2716 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002717 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002718 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2719 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002720 Instruction::CastOps opcode =
2721 (SrcBits == DstBits ? Instruction::BitCast :
2722 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2723 V = InsertCastBefore(opcode, V, I.getType(), I);
2724 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002725
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002726 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002728 }
2729 }
2730 }
2731
Chris Lattner7e708292002-06-25 16:13:24 +00002732 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002733}
2734
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002735/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2736/// instruction.
2737bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2738 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2739
2740 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2741 int NonNullOperand = -1;
2742 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2743 if (ST->isNullValue())
2744 NonNullOperand = 2;
2745 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2746 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2747 if (ST->isNullValue())
2748 NonNullOperand = 1;
2749
2750 if (NonNullOperand == -1)
2751 return false;
2752
2753 Value *SelectCond = SI->getOperand(0);
2754
2755 // Change the div/rem to use 'Y' instead of the select.
2756 I.setOperand(1, SI->getOperand(NonNullOperand));
2757
2758 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2759 // problem. However, the select, or the condition of the select may have
2760 // multiple uses. Based on our knowledge that the operand must be non-zero,
2761 // propagate the known value for the select into other uses of it, and
2762 // propagate a known value of the condition into its other users.
2763
2764 // If the select and condition only have a single use, don't bother with this,
2765 // early exit.
2766 if (SI->use_empty() && SelectCond->hasOneUse())
2767 return true;
2768
2769 // Scan the current block backward, looking for other uses of SI.
2770 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2771
2772 while (BBI != BBFront) {
2773 --BBI;
2774 // If we found a call to a function, we can't assume it will return, so
2775 // information from below it cannot be propagated above it.
2776 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2777 break;
2778
2779 // Replace uses of the select or its condition with the known values.
2780 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2781 I != E; ++I) {
2782 if (*I == SI) {
2783 *I = SI->getOperand(NonNullOperand);
2784 AddToWorkList(BBI);
2785 } else if (*I == SelectCond) {
2786 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2787 ConstantInt::getFalse();
2788 AddToWorkList(BBI);
2789 }
2790 }
2791
2792 // If we past the instruction, quit looking for it.
2793 if (&*BBI == SI)
2794 SI = 0;
2795 if (&*BBI == SelectCond)
2796 SelectCond = 0;
2797
2798 // If we ran out of things to eliminate, break out of the loop.
2799 if (SelectCond == 0 && SI == 0)
2800 break;
2801
2802 }
2803 return true;
2804}
2805
2806
Reid Spencer1628cec2006-10-26 06:15:43 +00002807/// This function implements the transforms on div instructions that work
2808/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2809/// used by the visitors to those instructions.
2810/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002811Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002812 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002813
Chris Lattner50b2ca42008-02-19 06:12:18 +00002814 // undef / X -> 0 for integer.
2815 // undef / X -> undef for FP (the undef could be a snan).
2816 if (isa<UndefValue>(Op0)) {
2817 if (Op0->getType()->isFPOrFPVector())
2818 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002819 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002820 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002821
2822 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002823 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002824 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002825
Reid Spencer1628cec2006-10-26 06:15:43 +00002826 return 0;
2827}
Misha Brukmanfd939082005-04-21 23:48:37 +00002828
Reid Spencer1628cec2006-10-26 06:15:43 +00002829/// This function implements the transforms common to both integer division
2830/// instructions (udiv and sdiv). It is called by the visitors to those integer
2831/// division instructions.
2832/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002833Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002836 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002837 if (Op0 == Op1) {
2838 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2839 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2840 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2841 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2842 }
2843
2844 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2845 return ReplaceInstUsesWith(I, CI);
2846 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002847
Reid Spencer1628cec2006-10-26 06:15:43 +00002848 if (Instruction *Common = commonDivTransforms(I))
2849 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002850
2851 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2852 // This does not apply for fdiv.
2853 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2854 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002855
2856 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2857 // div X, 1 == X
2858 if (RHS->equalsInt(1))
2859 return ReplaceInstUsesWith(I, Op0);
2860
2861 // (X / C1) / C2 -> X / (C1*C2)
2862 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2863 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2864 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002865 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2867 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002868 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002869 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002870 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002871
Reid Spencerbca0e382007-03-23 20:05:17 +00002872 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002873 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2874 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2875 return R;
2876 if (isa<PHINode>(Op0))
2877 if (Instruction *NV = FoldOpIntoPhi(I))
2878 return NV;
2879 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002880 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002881
Chris Lattnera2881962003-02-18 19:28:33 +00002882 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002883 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002884 if (LHS->equalsInt(0))
2885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2886
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002887 // It can't be division by zero, hence it must be division by one.
2888 if (I.getType() == Type::Int1Ty)
2889 return ReplaceInstUsesWith(I, Op0);
2890
Nick Lewycky895f0852008-11-27 20:21:08 +00002891 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2892 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2893 // div X, 1 == X
2894 if (X->isOne())
2895 return ReplaceInstUsesWith(I, Op0);
2896 }
2897
Reid Spencer1628cec2006-10-26 06:15:43 +00002898 return 0;
2899}
2900
2901Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904 // Handle the integer div common cases
2905 if (Instruction *Common = commonIDivTransforms(I))
2906 return Common;
2907
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002909 // X udiv C^2 -> X >> C
2910 // Check to see if this is an unsigned division with an exact power of 2,
2911 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002912 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002913 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002914 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002915
2916 // X udiv C, where C >= signbit
2917 if (C->getValue().isNegative()) {
2918 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2919 I);
2920 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2921 ConstantInt::get(I.getType(), 1));
2922 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 }
2924
2925 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002926 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 if (RHSI->getOpcode() == Instruction::Shl &&
2928 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002929 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002930 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002931 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002932 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002933 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002934 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002935 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002936 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002937 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002938 }
2939 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002940 }
2941
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2943 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002944 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002945 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002946 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002947 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002948 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002949 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002950 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002951 // Construct the "on true" case of the select
2952 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002953 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002954 Op0, TC, SI->getName()+".t");
2955 TSI = InsertNewInstBefore(TSI, I);
2956
2957 // Construct the "on false" case of the select
2958 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002959 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002960 Op0, FC, SI->getName()+".f");
2961 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002962
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002963 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002964 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002965 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002966 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002967 return 0;
2968}
2969
Reid Spencer1628cec2006-10-26 06:15:43 +00002970Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973 // Handle the integer div common cases
2974 if (Instruction *Common = commonIDivTransforms(I))
2975 return Common;
2976
2977 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978 // sdiv X, -1 == -X
2979 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002980 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002981 }
2982
2983 // If the sign bits of both operands are zero (i.e. we can prove they are
2984 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002985 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002986 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002987 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002988 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002989 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002990 }
2991 }
2992
2993 return 0;
2994}
2995
2996Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2997 return commonDivTransforms(I);
2998}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002999
Reid Spencer0a783f72006-11-02 01:53:59 +00003000/// This function implements the transforms on rem instructions that work
3001/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3002/// is used by the visitors to those instructions.
3003/// @brief Transforms common to all three rem instructions
3004Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003006
Chris Lattner50b2ca42008-02-19 06:12:18 +00003007 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3008 if (I.getType()->isFPOrFPVector())
3009 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003010 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003011 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003012 if (isa<UndefValue>(Op1))
3013 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003014
3015 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003016 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3017 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003018
Reid Spencer0a783f72006-11-02 01:53:59 +00003019 return 0;
3020}
3021
3022/// This function implements the transforms common to both integer remainder
3023/// instructions (urem and srem). It is called by the visitors to those integer
3024/// remainder instructions.
3025/// @brief Common integer remainder transforms
3026Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3028
3029 if (Instruction *common = commonRemTransforms(I))
3030 return common;
3031
Dale Johannesened6af242009-01-21 00:35:19 +00003032 // 0 % X == 0 for integer, we don't need to preserve faults!
3033 if (Constant *LHS = dyn_cast<Constant>(Op0))
3034 if (LHS->isNullValue())
3035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3036
Chris Lattner857e8cd2004-12-12 21:48:58 +00003037 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003038 // X % 0 == undef, we don't need to preserve faults!
3039 if (RHS->equalsInt(0))
3040 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3041
Chris Lattnera2881962003-02-18 19:28:33 +00003042 if (RHS->equalsInt(1)) // X % 1 == 0
3043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
Chris Lattner97943922006-02-28 05:49:21 +00003045 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3046 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3047 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3048 return R;
3049 } else if (isa<PHINode>(Op0I)) {
3050 if (Instruction *NV = FoldOpIntoPhi(I))
3051 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003052 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003053
3054 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003055 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003056 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003057 }
Chris Lattnera2881962003-02-18 19:28:33 +00003058 }
3059
Reid Spencer0a783f72006-11-02 01:53:59 +00003060 return 0;
3061}
3062
3063Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3065
3066 if (Instruction *common = commonIRemTransforms(I))
3067 return common;
3068
3069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3070 // X urem C^2 -> X and C
3071 // Check to see if this is an unsigned remainder with an exact power of 2,
3072 // if so, convert to a bitwise and.
3073 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003074 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003075 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003076 }
3077
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003078 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003079 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3080 if (RHSI->getOpcode() == Instruction::Shl &&
3081 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003082 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003083 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003084 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003085 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003086 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003087 }
3088 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003089 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003090
Reid Spencer0a783f72006-11-02 01:53:59 +00003091 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3092 // where C1&C2 are powers of two.
3093 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3094 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3095 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3096 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 if ((STO->getValue().isPowerOf2()) &&
3098 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003099 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003100 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003101 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003102 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003103 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003104 }
3105 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003106 }
3107
Chris Lattner3f5b8772002-05-06 16:14:14 +00003108 return 0;
3109}
3110
Reid Spencer0a783f72006-11-02 01:53:59 +00003111Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3113
Dan Gohmancff55092007-11-05 23:16:33 +00003114 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003115 if (Instruction *common = commonIRemTransforms(I))
3116 return common;
3117
3118 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003119 if (!isa<Constant>(RHSNeg) ||
3120 (isa<ConstantInt>(RHSNeg) &&
3121 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003122 // X % -Y -> X % Y
3123 AddUsesToWorkList(I);
3124 I.setOperand(1, RHSNeg);
3125 return &I;
3126 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003127
Dan Gohmancff55092007-11-05 23:16:33 +00003128 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003129 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003130 if (I.getType()->isInteger()) {
3131 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3132 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3133 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003134 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003135 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003136 }
3137
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003138 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003139 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3140 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003141
Nick Lewycky9dce8732008-12-20 16:48:00 +00003142 bool hasNegative = false;
3143 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3145 if (RHS->getValue().isNegative())
3146 hasNegative = true;
3147
3148 if (hasNegative) {
3149 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003150 for (unsigned i = 0; i != VWidth; ++i) {
3151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3152 if (RHS->getValue().isNegative())
3153 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3154 else
3155 Elts[i] = RHS;
3156 }
3157 }
3158
3159 Constant *NewRHSV = ConstantVector::get(Elts);
3160 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003161 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003162 I.setOperand(1, NewRHSV);
3163 return &I;
3164 }
3165 }
3166 }
3167
Reid Spencer0a783f72006-11-02 01:53:59 +00003168 return 0;
3169}
3170
3171Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003172 return commonRemTransforms(I);
3173}
3174
Chris Lattner457dd822004-06-09 07:59:58 +00003175// isOneBitSet - Return true if there is exactly one bit set in the specified
3176// constant.
3177static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003178 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003179}
3180
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003181// isHighOnes - Return true if the constant is of the form 1+0+.
3182// This is the same as lowones(~X).
3183static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003184 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003185}
3186
Reid Spencere4d87aa2006-12-23 06:05:41 +00003187/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003188/// are carefully arranged to allow folding of expressions such as:
3189///
3190/// (A < B) | (A > B) --> (A != B)
3191///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003192/// Note that this is only valid if the first and second predicates have the
3193/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003194///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003195/// Three bits are used to represent the condition, as follows:
3196/// 0 A > B
3197/// 1 A == B
3198/// 2 A < B
3199///
3200/// <=> Value Definition
3201/// 000 0 Always false
3202/// 001 1 A > B
3203/// 010 2 A == B
3204/// 011 3 A >= B
3205/// 100 4 A < B
3206/// 101 5 A != B
3207/// 110 6 A <= B
3208/// 111 7 Always true
3209///
3210static unsigned getICmpCode(const ICmpInst *ICI) {
3211 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003212 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003213 case ICmpInst::ICMP_UGT: return 1; // 001
3214 case ICmpInst::ICMP_SGT: return 1; // 001
3215 case ICmpInst::ICMP_EQ: return 2; // 010
3216 case ICmpInst::ICMP_UGE: return 3; // 011
3217 case ICmpInst::ICMP_SGE: return 3; // 011
3218 case ICmpInst::ICMP_ULT: return 4; // 100
3219 case ICmpInst::ICMP_SLT: return 4; // 100
3220 case ICmpInst::ICMP_NE: return 5; // 101
3221 case ICmpInst::ICMP_ULE: return 6; // 110
3222 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003223 // True -> 7
3224 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003225 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003226 return 0;
3227 }
3228}
3229
Evan Cheng8db90722008-10-14 17:15:11 +00003230/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3231/// predicate into a three bit mask. It also returns whether it is an ordered
3232/// predicate by reference.
3233static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3234 isOrdered = false;
3235 switch (CC) {
3236 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3237 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003238 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3239 case FCmpInst::FCMP_UGT: return 1; // 001
3240 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3241 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003242 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3243 case FCmpInst::FCMP_UGE: return 3; // 011
3244 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3245 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003246 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3247 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003248 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3249 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003250 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003251 default:
3252 // Not expecting FCMP_FALSE and FCMP_TRUE;
3253 assert(0 && "Unexpected FCmp predicate!");
3254 return 0;
3255 }
3256}
3257
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258/// getICmpValue - This is the complement of getICmpCode, which turns an
3259/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003260/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003261/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003262static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3263 switch (code) {
3264 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003265 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003266 case 1:
3267 if (sign)
3268 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3269 else
3270 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3271 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3272 case 3:
3273 if (sign)
3274 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3275 else
3276 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3277 case 4:
3278 if (sign)
3279 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3280 else
3281 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3282 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3283 case 6:
3284 if (sign)
3285 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3286 else
3287 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003288 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003289 }
3290}
3291
Evan Cheng8db90722008-10-14 17:15:11 +00003292/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3293/// opcode and two operands into either a FCmp instruction. isordered is passed
3294/// in to determine which kind of predicate to use in the new fcmp instruction.
3295static Value *getFCmpValue(bool isordered, unsigned code,
3296 Value *LHS, Value *RHS) {
3297 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003298 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003299 case 0:
3300 if (isordered)
3301 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3302 else
3303 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3304 case 1:
3305 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003306 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3307 else
3308 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003309 case 2:
3310 if (isordered)
3311 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3312 else
3313 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003314 case 3:
3315 if (isordered)
3316 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3317 else
3318 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3319 case 4:
3320 if (isordered)
3321 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3322 else
3323 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3324 case 5:
3325 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003326 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3327 else
3328 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3329 case 6:
3330 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003331 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3332 else
3333 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003334 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003335 }
3336}
3337
Chris Lattnerb9553d62008-11-16 04:55:20 +00003338/// PredicatesFoldable - Return true if both predicates match sign or if at
3339/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003340static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3341 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003342 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3343 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003344}
3345
3346namespace {
3347// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3348struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003349 InstCombiner &IC;
3350 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351 ICmpInst::Predicate pred;
3352 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3353 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3354 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003355 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3357 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003358 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3359 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003360 return false;
3361 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362 Instruction *apply(Instruction &Log) const {
3363 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3364 if (ICI->getOperand(0) != LHS) {
3365 assert(ICI->getOperand(1) == LHS);
3366 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003367 }
3368
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003369 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003371 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003372 unsigned Code;
3373 switch (Log.getOpcode()) {
3374 case Instruction::And: Code = LHSCode & RHSCode; break;
3375 case Instruction::Or: Code = LHSCode | RHSCode; break;
3376 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003377 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003378 }
3379
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003380 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3381 ICmpInst::isSignedPredicate(ICI->getPredicate());
3382
3383 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003384 if (Instruction *I = dyn_cast<Instruction>(RV))
3385 return I;
3386 // Otherwise, it's a constant boolean value...
3387 return IC.ReplaceInstUsesWith(Log, RV);
3388 }
3389};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003390} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003391
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003392// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3393// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003394// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003395Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003396 ConstantInt *OpRHS,
3397 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003398 BinaryOperator &TheAnd) {
3399 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003400 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003401 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003402 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003403
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003404 switch (Op->getOpcode()) {
3405 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003406 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003407 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003408 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003409 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003410 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003411 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003412 }
3413 break;
3414 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003415 if (Together == AndRHS) // (X | C) & C --> C
3416 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003417
Chris Lattner6e7ba452005-01-01 16:22:27 +00003418 if (Op->hasOneUse() && Together != OpRHS) {
3419 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003420 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003421 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003422 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003423 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003424 }
3425 break;
3426 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003427 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003428 // Adding a one to a single bit bit-field should be turned into an XOR
3429 // of the bit. First thing to check is to see if this AND is with a
3430 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003431 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003432
3433 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003434 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003435 // Ok, at this point, we know that we are masking the result of the
3436 // ADD down to exactly one bit. If the constant we are adding has
3437 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003438 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003439
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003440 // Check to see if any bits below the one bit set in AndRHSV are set.
3441 if ((AddRHS & (AndRHSV-1)) == 0) {
3442 // If not, the only thing that can effect the output of the AND is
3443 // the bit specified by AndRHSV. If that bit is set, the effect of
3444 // the XOR is to toggle the bit. If it is clear, then the ADD has
3445 // no effect.
3446 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3447 TheAnd.setOperand(0, X);
3448 return &TheAnd;
3449 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003450 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003451 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003452 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003453 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003454 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003455 }
3456 }
3457 }
3458 }
3459 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003460
3461 case Instruction::Shl: {
3462 // We know that the AND will not produce any of the bits shifted in, so if
3463 // the anded constant includes them, clear them now!
3464 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003465 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003466 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003467 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3468 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003469
Zhou Sheng290bec52007-03-29 08:15:12 +00003470 if (CI->getValue() == ShlMask) {
3471 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003472 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3473 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003474 TheAnd.setOperand(1, CI);
3475 return &TheAnd;
3476 }
3477 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003478 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003479 case Instruction::LShr:
3480 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003481 // We know that the AND will not produce any of the bits shifted in, so if
3482 // the anded constant includes them, clear them now! This only applies to
3483 // unsigned shifts, because a signed shr may bring in set bits!
3484 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003485 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003486 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003487 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3488 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003489
Zhou Sheng290bec52007-03-29 08:15:12 +00003490 if (CI->getValue() == ShrMask) {
3491 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003492 return ReplaceInstUsesWith(TheAnd, Op);
3493 } else if (CI != AndRHS) {
3494 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3495 return &TheAnd;
3496 }
3497 break;
3498 }
3499 case Instruction::AShr:
3500 // Signed shr.
3501 // See if this is shifting in some sign extension, then masking it out
3502 // with an and.
3503 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003504 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003505 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003506 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3507 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003508 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003509 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003510 // Make the argument unsigned.
3511 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003512 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003513 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003514 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003516 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003517 }
3518 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 }
3520 return 0;
3521}
3522
Chris Lattner8b170942002-08-09 23:47:40 +00003523
Chris Lattnera96879a2004-09-29 17:40:11 +00003524/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3525/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003526/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3527/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003528/// insert new instructions.
3529Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003530 bool isSigned, bool Inside,
3531 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003532 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003533 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003534 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003535
Chris Lattnera96879a2004-09-29 17:40:11 +00003536 if (Inside) {
3537 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003538 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003539
Reid Spencere4d87aa2006-12-23 06:05:41 +00003540 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003541 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003542 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003543 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3544 return new ICmpInst(pred, V, Hi);
3545 }
3546
3547 // Emit V-Lo <u Hi-Lo
3548 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003550 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003551 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3552 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003553 }
3554
3555 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003556 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003557
Reid Spencere4e40032007-03-21 23:19:50 +00003558 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003559 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003560 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003561 ICmpInst::Predicate pred = (isSigned ?
3562 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3563 return new ICmpInst(pred, V, Hi);
3564 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003565
Reid Spencere4e40032007-03-21 23:19:50 +00003566 // Emit V-Lo >u Hi-1-Lo
3567 // Note that Hi has already had one subtracted from it, above.
3568 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003569 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003570 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3572 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003573}
3574
Chris Lattner7203e152005-09-18 07:22:02 +00003575// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3576// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3577// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3578// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003579static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003580 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003581 uint32_t BitWidth = Val->getType()->getBitWidth();
3582 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003583
3584 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003585 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003586 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003587 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003588 return true;
3589}
3590
Chris Lattner7203e152005-09-18 07:22:02 +00003591/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3592/// where isSub determines whether the operator is a sub. If we can fold one of
3593/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003594///
3595/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3596/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3597/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3598///
3599/// return (A +/- B).
3600///
3601Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003602 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003603 Instruction &I) {
3604 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3605 if (!LHSI || LHSI->getNumOperands() != 2 ||
3606 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3607
3608 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3609
3610 switch (LHSI->getOpcode()) {
3611 default: return 0;
3612 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003613 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003614 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003615 if ((Mask->getValue().countLeadingZeros() +
3616 Mask->getValue().countPopulation()) ==
3617 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003618 break;
3619
3620 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3621 // part, we don't need any explicit masks to take them out of A. If that
3622 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003623 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003624 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003625 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003626 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003627 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003628 break;
3629 }
3630 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003631 return 0;
3632 case Instruction::Or:
3633 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003634 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003635 if ((Mask->getValue().countLeadingZeros() +
3636 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003637 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003638 break;
3639 return 0;
3640 }
3641
3642 Instruction *New;
3643 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003644 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003645 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003646 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003647 return InsertNewInstBefore(New, I);
3648}
3649
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003650/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3651Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3652 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003653 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003654 ConstantInt *LHSCst, *RHSCst;
3655 ICmpInst::Predicate LHSCC, RHSCC;
3656
Chris Lattnerea065fb2008-11-16 05:10:52 +00003657 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003658 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003659 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003660 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003661
3662 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3663 // where C is a power of 2
3664 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3665 LHSCst->getValue().isPowerOf2()) {
3666 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3667 InsertNewInstBefore(NewOr, I);
3668 return new ICmpInst(LHSCC, NewOr, LHSCst);
3669 }
3670
3671 // From here on, we only handle:
3672 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3673 if (Val != Val2) return 0;
3674
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003675 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3676 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3677 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3678 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3679 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3680 return 0;
3681
3682 // We can't fold (ugt x, C) & (sgt x, C2).
3683 if (!PredicatesFoldable(LHSCC, RHSCC))
3684 return 0;
3685
3686 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003687 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003688 if (ICmpInst::isSignedPredicate(LHSCC) ||
3689 (ICmpInst::isEquality(LHSCC) &&
3690 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003691 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003692 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003693 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3694
3695 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003696 std::swap(LHS, RHS);
3697 std::swap(LHSCst, RHSCst);
3698 std::swap(LHSCC, RHSCC);
3699 }
3700
3701 // At this point, we know we have have two icmp instructions
3702 // comparing a value against two constants and and'ing the result
3703 // together. Because of the above check, we know that we only have
3704 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3705 // (from the FoldICmpLogical check above), that the two constants
3706 // are not equal and that the larger constant is on the RHS
3707 assert(LHSCst != RHSCst && "Compares not folded above?");
3708
3709 switch (LHSCC) {
3710 default: assert(0 && "Unknown integer condition code!");
3711 case ICmpInst::ICMP_EQ:
3712 switch (RHSCC) {
3713 default: assert(0 && "Unknown integer condition code!");
3714 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3715 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3716 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3717 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3718 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3719 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3720 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3721 return ReplaceInstUsesWith(I, LHS);
3722 }
3723 case ICmpInst::ICMP_NE:
3724 switch (RHSCC) {
3725 default: assert(0 && "Unknown integer condition code!");
3726 case ICmpInst::ICMP_ULT:
3727 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3728 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3729 break; // (X != 13 & X u< 15) -> no change
3730 case ICmpInst::ICMP_SLT:
3731 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3732 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3733 break; // (X != 13 & X s< 15) -> no change
3734 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3735 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3736 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3737 return ReplaceInstUsesWith(I, RHS);
3738 case ICmpInst::ICMP_NE:
3739 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3740 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3741 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3742 Val->getName()+".off");
3743 InsertNewInstBefore(Add, I);
3744 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3745 ConstantInt::get(Add->getType(), 1));
3746 }
3747 break; // (X != 13 & X != 15) -> no change
3748 }
3749 break;
3750 case ICmpInst::ICMP_ULT:
3751 switch (RHSCC) {
3752 default: assert(0 && "Unknown integer condition code!");
3753 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3754 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3755 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3756 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3757 break;
3758 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3759 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3760 return ReplaceInstUsesWith(I, LHS);
3761 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3762 break;
3763 }
3764 break;
3765 case ICmpInst::ICMP_SLT:
3766 switch (RHSCC) {
3767 default: assert(0 && "Unknown integer condition code!");
3768 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3769 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3770 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3771 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3772 break;
3773 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3774 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3775 return ReplaceInstUsesWith(I, LHS);
3776 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3777 break;
3778 }
3779 break;
3780 case ICmpInst::ICMP_UGT:
3781 switch (RHSCC) {
3782 default: assert(0 && "Unknown integer condition code!");
3783 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3784 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3785 return ReplaceInstUsesWith(I, RHS);
3786 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3787 break;
3788 case ICmpInst::ICMP_NE:
3789 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3790 return new ICmpInst(LHSCC, Val, RHSCst);
3791 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003792 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003793 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3794 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3795 break;
3796 }
3797 break;
3798 case ICmpInst::ICMP_SGT:
3799 switch (RHSCC) {
3800 default: assert(0 && "Unknown integer condition code!");
3801 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3802 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3803 return ReplaceInstUsesWith(I, RHS);
3804 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3805 break;
3806 case ICmpInst::ICMP_NE:
3807 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3808 return new ICmpInst(LHSCC, Val, RHSCst);
3809 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003810 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3812 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3813 break;
3814 }
3815 break;
3816 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003817
3818 return 0;
3819}
3820
3821
Chris Lattner7e708292002-06-25 16:13:24 +00003822Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003823 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003824 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003825
Chris Lattnere87597f2004-10-16 18:11:37 +00003826 if (isa<UndefValue>(Op1)) // X & undef -> 0
3827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3828
Chris Lattner6e7ba452005-01-01 16:22:27 +00003829 // and X, X = X
3830 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003831 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003832
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003833 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003834 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003835 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003836 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003837 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003838 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003839 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003840 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003841 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003842 } else if (isa<ConstantAggregateZero>(Op1)) {
3843 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003844 }
3845 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003846
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003847 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003848 const APInt& AndRHSMask = AndRHS->getValue();
3849 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003850
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003851 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003852 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003853 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003854 Value *Op0LHS = Op0I->getOperand(0);
3855 Value *Op0RHS = Op0I->getOperand(1);
3856 switch (Op0I->getOpcode()) {
3857 case Instruction::Xor:
3858 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003859 // If the mask is only needed on one incoming arm, push it up.
3860 if (Op0I->hasOneUse()) {
3861 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3862 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003863 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003864 Op0RHS->getName()+".masked");
3865 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003866 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003867 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003868 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003869 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003870 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3871 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003872 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003873 Op0LHS->getName()+".masked");
3874 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003875 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003876 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3877 }
3878 }
3879
Chris Lattner6e7ba452005-01-01 16:22:27 +00003880 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003881 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003882 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3883 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3884 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3885 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003887 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003888 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003889 break;
3890
3891 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003892 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3893 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3894 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3895 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003896 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003897
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003898 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3899 // has 1's for all bits that the subtraction with A might affect.
3900 if (Op0I->hasOneUse()) {
3901 uint32_t BitWidth = AndRHSMask.getBitWidth();
3902 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3903 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3904
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003905 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003906 if (!(A && A->isZero()) && // avoid infinite recursion.
3907 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003908 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3909 InsertNewInstBefore(NewNeg, I);
3910 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3911 }
3912 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003913 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003914
3915 case Instruction::Shl:
3916 case Instruction::LShr:
3917 // (1 << x) & 1 --> zext(x == 0)
3918 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003919 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003920 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3921 Constant::getNullValue(I.getType()));
3922 InsertNewInstBefore(NewICmp, I);
3923 return new ZExtInst(NewICmp, I.getType());
3924 }
3925 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003926 }
3927
Chris Lattner58403262003-07-23 19:25:52 +00003928 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003929 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003930 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003931 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003932 // If this is an integer truncation or change from signed-to-unsigned, and
3933 // if the source is an and/or with immediate, transform it. This
3934 // frequently occurs for bitfield accesses.
3935 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003936 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003937 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003938 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003939 if (CastOp->getOpcode() == Instruction::And) {
3940 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003941 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3942 // This will fold the two constants together, which may allow
3943 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003944 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003945 CastOp->getOperand(0), I.getType(),
3946 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003947 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003948 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003949 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003950 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003951 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003952 } else if (CastOp->getOpcode() == Instruction::Or) {
3953 // Change: and (cast (or X, C1) to T), C2
3954 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003955 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003956 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3957 return ReplaceInstUsesWith(I, AndRHS);
3958 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003959 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003960 }
Chris Lattner06782f82003-07-23 19:36:21 +00003961 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003962
3963 // Try to fold constant and into select arguments.
3964 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003965 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003966 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003967 if (isa<PHINode>(Op0))
3968 if (Instruction *NV = FoldOpIntoPhi(I))
3969 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003970 }
3971
Chris Lattner8d969642003-03-10 23:06:50 +00003972 Value *Op0NotVal = dyn_castNotVal(Op0);
3973 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003974
Chris Lattner5b62aa72004-06-18 06:07:51 +00003975 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3977
Misha Brukmancb6267b2004-07-30 12:50:08 +00003978 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003979 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003980 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003981 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003982 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003983 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003984 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003985
3986 {
Chris Lattner003b6202007-06-15 05:58:24 +00003987 Value *A = 0, *B = 0, *C = 0, *D = 0;
3988 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003989 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3990 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003991
3992 // (A|B) & ~(A&B) -> A^B
3993 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3994 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003995 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003996 }
3997 }
3998
3999 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004000 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4001 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004002
4003 // ~(A&B) & (A|B) -> A^B
4004 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4005 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004006 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004007 }
4008 }
Chris Lattner64daab52006-04-01 08:03:55 +00004009
4010 if (Op0->hasOneUse() &&
4011 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4012 if (A == Op1) { // (A^B)&A -> A&(A^B)
4013 I.swapOperands(); // Simplify below
4014 std::swap(Op0, Op1);
4015 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4016 cast<BinaryOperator>(Op0)->swapOperands();
4017 I.swapOperands(); // Simplify below
4018 std::swap(Op0, Op1);
4019 }
4020 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004021
Chris Lattner64daab52006-04-01 08:03:55 +00004022 if (Op1->hasOneUse() &&
4023 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4024 if (B == Op0) { // B&(A^B) -> B&(B^A)
4025 cast<BinaryOperator>(Op1)->swapOperands();
4026 std::swap(A, B);
4027 }
4028 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004029 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004030 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004031 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004032 }
4033 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004034
4035 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004036 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4037 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4038 return BinaryOperator::CreateAnd(A, Op1);
4039 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4040 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4041 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004042 }
4043
Reid Spencere4d87aa2006-12-23 06:05:41 +00004044 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4045 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4046 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004047 return R;
4048
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004049 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4050 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4051 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004052 }
4053
Chris Lattner6fc205f2006-05-05 06:39:07 +00004054 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004055 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4056 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4057 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4058 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004059 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004060 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004061 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4062 I.getType(), TD) &&
4063 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4064 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004065 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004066 Op1C->getOperand(0),
4067 I.getName());
4068 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004070 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004071 }
Chris Lattnere511b742006-11-14 07:46:50 +00004072
4073 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004074 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4075 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4076 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004077 SI0->getOperand(1) == SI1->getOperand(1) &&
4078 (SI0->hasOneUse() || SI1->hasOneUse())) {
4079 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004081 SI1->getOperand(0),
4082 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004084 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004085 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004086 }
4087
Evan Cheng8db90722008-10-14 17:15:11 +00004088 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004089 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4090 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4091 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004092 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4093 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004094 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4095 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4096 // If either of the constants are nans, then the whole thing returns
4097 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004098 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004099 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4100 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4101 RHS->getOperand(0));
4102 }
Evan Cheng8db90722008-10-14 17:15:11 +00004103 } else {
4104 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4105 FCmpInst::Predicate Op0CC, Op1CC;
4106 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4107 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004108 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4109 // Swap RHS operands to match LHS.
4110 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4111 std::swap(Op1LHS, Op1RHS);
4112 }
Evan Cheng8db90722008-10-14 17:15:11 +00004113 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4114 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4115 if (Op0CC == Op1CC)
4116 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4117 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4118 Op1CC == FCmpInst::FCMP_FALSE)
4119 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4120 else if (Op0CC == FCmpInst::FCMP_TRUE)
4121 return ReplaceInstUsesWith(I, Op1);
4122 else if (Op1CC == FCmpInst::FCMP_TRUE)
4123 return ReplaceInstUsesWith(I, Op0);
4124 bool Op0Ordered;
4125 bool Op1Ordered;
4126 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4127 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4128 if (Op1Pred == 0) {
4129 std::swap(Op0, Op1);
4130 std::swap(Op0Pred, Op1Pred);
4131 std::swap(Op0Ordered, Op1Ordered);
4132 }
4133 if (Op0Pred == 0) {
4134 // uno && ueq -> uno && (uno || eq) -> ueq
4135 // ord && olt -> ord && (ord && lt) -> olt
4136 if (Op0Ordered == Op1Ordered)
4137 return ReplaceInstUsesWith(I, Op1);
4138 // uno && oeq -> uno && (ord && eq) -> false
4139 // uno && ord -> false
4140 if (!Op0Ordered)
4141 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4142 // ord && ueq -> ord && (uno || eq) -> oeq
4143 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4144 Op0LHS, Op0RHS));
4145 }
4146 }
4147 }
4148 }
Chris Lattner99c65742007-10-24 05:38:08 +00004149 }
4150 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004151
Chris Lattner7e708292002-06-25 16:13:24 +00004152 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004153}
4154
Chris Lattner8c34cd22008-10-05 02:13:19 +00004155/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4156/// capable of providing pieces of a bswap. The subexpression provides pieces
4157/// of a bswap if it is proven that each of the non-zero bytes in the output of
4158/// the expression came from the corresponding "byte swapped" byte in some other
4159/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4160/// we know that the expression deposits the low byte of %X into the high byte
4161/// of the bswap result and that all other bytes are zero. This expression is
4162/// accepted, the high byte of ByteValues is set to X to indicate a correct
4163/// match.
4164///
4165/// This function returns true if the match was unsuccessful and false if so.
4166/// On entry to the function the "OverallLeftShift" is a signed integer value
4167/// indicating the number of bytes that the subexpression is later shifted. For
4168/// example, if the expression is later right shifted by 16 bits, the
4169/// OverallLeftShift value would be -2 on entry. This is used to specify which
4170/// byte of ByteValues is actually being set.
4171///
4172/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4173/// byte is masked to zero by a user. For example, in (X & 255), X will be
4174/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4175/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4176/// always in the local (OverallLeftShift) coordinate space.
4177///
4178static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4179 SmallVector<Value*, 8> &ByteValues) {
4180 if (Instruction *I = dyn_cast<Instruction>(V)) {
4181 // If this is an or instruction, it may be an inner node of the bswap.
4182 if (I->getOpcode() == Instruction::Or) {
4183 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4184 ByteValues) ||
4185 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4186 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004187 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004188
4189 // If this is a logical shift by a constant multiple of 8, recurse with
4190 // OverallLeftShift and ByteMask adjusted.
4191 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4192 unsigned ShAmt =
4193 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4194 // Ensure the shift amount is defined and of a byte value.
4195 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4196 return true;
4197
4198 unsigned ByteShift = ShAmt >> 3;
4199 if (I->getOpcode() == Instruction::Shl) {
4200 // X << 2 -> collect(X, +2)
4201 OverallLeftShift += ByteShift;
4202 ByteMask >>= ByteShift;
4203 } else {
4204 // X >>u 2 -> collect(X, -2)
4205 OverallLeftShift -= ByteShift;
4206 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004207 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004208 }
4209
4210 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4211 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4212
4213 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4214 ByteValues);
4215 }
4216
4217 // If this is a logical 'and' with a mask that clears bytes, clear the
4218 // corresponding bytes in ByteMask.
4219 if (I->getOpcode() == Instruction::And &&
4220 isa<ConstantInt>(I->getOperand(1))) {
4221 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4222 unsigned NumBytes = ByteValues.size();
4223 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4224 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4225
4226 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4227 // If this byte is masked out by a later operation, we don't care what
4228 // the and mask is.
4229 if ((ByteMask & (1 << i)) == 0)
4230 continue;
4231
4232 // If the AndMask is all zeros for this byte, clear the bit.
4233 APInt MaskB = AndMask & Byte;
4234 if (MaskB == 0) {
4235 ByteMask &= ~(1U << i);
4236 continue;
4237 }
4238
4239 // If the AndMask is not all ones for this byte, it's not a bytezap.
4240 if (MaskB != Byte)
4241 return true;
4242
4243 // Otherwise, this byte is kept.
4244 }
4245
4246 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4247 ByteValues);
4248 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004249 }
4250
Chris Lattner8c34cd22008-10-05 02:13:19 +00004251 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4252 // the input value to the bswap. Some observations: 1) if more than one byte
4253 // is demanded from this input, then it could not be successfully assembled
4254 // into a byteswap. At least one of the two bytes would not be aligned with
4255 // their ultimate destination.
4256 if (!isPowerOf2_32(ByteMask)) return true;
4257 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004258
Chris Lattner8c34cd22008-10-05 02:13:19 +00004259 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4260 // is demanded, it needs to go into byte 0 of the result. This means that the
4261 // byte needs to be shifted until it lands in the right byte bucket. The
4262 // shift amount depends on the position: if the byte is coming from the high
4263 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4264 // low part, it must be shifted left.
4265 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4266 if (InputByteNo < ByteValues.size()/2) {
4267 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4268 return true;
4269 } else {
4270 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4271 return true;
4272 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004273
4274 // If the destination byte value is already defined, the values are or'd
4275 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004276 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004277 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004278 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004279 return false;
4280}
4281
4282/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4283/// If so, insert the new bswap intrinsic and return it.
4284Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004285 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004286 if (!ITy || ITy->getBitWidth() % 16 ||
4287 // ByteMask only allows up to 32-byte values.
4288 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004289 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004290
4291 /// ByteValues - For each byte of the result, we keep track of which value
4292 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004293 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004294 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004295
4296 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004297 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4298 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004299 return 0;
4300
4301 // Check to see if all of the bytes come from the same value.
4302 Value *V = ByteValues[0];
4303 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4304
4305 // Check to make sure that all of the bytes come from the same value.
4306 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4307 if (ByteValues[i] != V)
4308 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004309 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004310 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004311 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004312 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004313}
4314
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004315/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4316/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4317/// we can simplify this expression to "cond ? C : D or B".
4318static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4319 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004320 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004321 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004322 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004323 return 0;
4324
Chris Lattnera6a474d2008-11-16 04:26:55 +00004325 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004326 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004327 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004328 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004329 return SelectInst::Create(Cond, C, B);
4330 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004331 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004332 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004333 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004334 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004335 return 0;
4336}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004337
Chris Lattner69d4ced2008-11-16 05:20:07 +00004338/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4339Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4340 ICmpInst *LHS, ICmpInst *RHS) {
4341 Value *Val, *Val2;
4342 ConstantInt *LHSCst, *RHSCst;
4343 ICmpInst::Predicate LHSCC, RHSCC;
4344
4345 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4346 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4347 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4348 return 0;
4349
4350 // From here on, we only handle:
4351 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4352 if (Val != Val2) return 0;
4353
4354 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4355 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4356 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4357 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4358 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4359 return 0;
4360
4361 // We can't fold (ugt x, C) | (sgt x, C2).
4362 if (!PredicatesFoldable(LHSCC, RHSCC))
4363 return 0;
4364
4365 // Ensure that the larger constant is on the RHS.
4366 bool ShouldSwap;
4367 if (ICmpInst::isSignedPredicate(LHSCC) ||
4368 (ICmpInst::isEquality(LHSCC) &&
4369 ICmpInst::isSignedPredicate(RHSCC)))
4370 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4371 else
4372 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4373
4374 if (ShouldSwap) {
4375 std::swap(LHS, RHS);
4376 std::swap(LHSCst, RHSCst);
4377 std::swap(LHSCC, RHSCC);
4378 }
4379
4380 // At this point, we know we have have two icmp instructions
4381 // comparing a value against two constants and or'ing the result
4382 // together. Because of the above check, we know that we only have
4383 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4384 // FoldICmpLogical check above), that the two constants are not
4385 // equal.
4386 assert(LHSCst != RHSCst && "Compares not folded above?");
4387
4388 switch (LHSCC) {
4389 default: assert(0 && "Unknown integer condition code!");
4390 case ICmpInst::ICMP_EQ:
4391 switch (RHSCC) {
4392 default: assert(0 && "Unknown integer condition code!");
4393 case ICmpInst::ICMP_EQ:
4394 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4395 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4396 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4397 Val->getName()+".off");
4398 InsertNewInstBefore(Add, I);
4399 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4400 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4401 }
4402 break; // (X == 13 | X == 15) -> no change
4403 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4404 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4405 break;
4406 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4407 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4408 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4409 return ReplaceInstUsesWith(I, RHS);
4410 }
4411 break;
4412 case ICmpInst::ICMP_NE:
4413 switch (RHSCC) {
4414 default: assert(0 && "Unknown integer condition code!");
4415 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4416 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4417 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4418 return ReplaceInstUsesWith(I, LHS);
4419 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4420 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4421 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4422 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4423 }
4424 break;
4425 case ICmpInst::ICMP_ULT:
4426 switch (RHSCC) {
4427 default: assert(0 && "Unknown integer condition code!");
4428 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4429 break;
4430 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4431 // If RHSCst is [us]MAXINT, it is always false. Not handling
4432 // this can cause overflow.
4433 if (RHSCst->isMaxValue(false))
4434 return ReplaceInstUsesWith(I, LHS);
4435 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4436 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4437 break;
4438 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4439 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4440 return ReplaceInstUsesWith(I, RHS);
4441 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4442 break;
4443 }
4444 break;
4445 case ICmpInst::ICMP_SLT:
4446 switch (RHSCC) {
4447 default: assert(0 && "Unknown integer condition code!");
4448 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4449 break;
4450 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4451 // If RHSCst is [us]MAXINT, it is always false. Not handling
4452 // this can cause overflow.
4453 if (RHSCst->isMaxValue(true))
4454 return ReplaceInstUsesWith(I, LHS);
4455 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4456 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4457 break;
4458 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4459 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4460 return ReplaceInstUsesWith(I, RHS);
4461 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4462 break;
4463 }
4464 break;
4465 case ICmpInst::ICMP_UGT:
4466 switch (RHSCC) {
4467 default: assert(0 && "Unknown integer condition code!");
4468 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4469 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4470 return ReplaceInstUsesWith(I, LHS);
4471 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4472 break;
4473 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4474 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4475 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4476 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4477 break;
4478 }
4479 break;
4480 case ICmpInst::ICMP_SGT:
4481 switch (RHSCC) {
4482 default: assert(0 && "Unknown integer condition code!");
4483 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4484 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4485 return ReplaceInstUsesWith(I, LHS);
4486 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4487 break;
4488 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4489 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4490 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4491 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4492 break;
4493 }
4494 break;
4495 }
4496 return 0;
4497}
4498
Bill Wendlinga698a472008-12-01 08:23:25 +00004499/// FoldOrWithConstants - This helper function folds:
4500///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004501/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004502///
4503/// into:
4504///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004505/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004506///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004507/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004508Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004509 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004510 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4511 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004512
Bill Wendling286a0542008-12-02 06:24:20 +00004513 Value *V1 = 0;
4514 ConstantInt *CI2 = 0;
4515 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004516
Bill Wendling29976b92008-12-02 06:18:11 +00004517 APInt Xor = CI1->getValue() ^ CI2->getValue();
4518 if (!Xor.isAllOnesValue()) return 0;
4519
Bill Wendling286a0542008-12-02 06:24:20 +00004520 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004521 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004522 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4523 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004524 }
4525
4526 return 0;
4527}
4528
Chris Lattner7e708292002-06-25 16:13:24 +00004529Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004530 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004532
Chris Lattner42593e62007-03-24 23:56:43 +00004533 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004534 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004535
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004536 // or X, X = X
4537 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004538 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004539
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004540 // See if we can simplify any instructions used by the instruction whose sole
4541 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004542 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004543 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004544 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004545 } else if (isa<ConstantAggregateZero>(Op1)) {
4546 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4547 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4548 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4549 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004550 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004551
4552
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004553
Chris Lattner3f5b8772002-05-06 16:14:14 +00004554 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004555 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004556 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004557 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4558 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004559 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004560 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004561 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004562 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004563 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004564 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004565
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004566 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4567 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004568 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004569 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004570 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004571 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004572 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004573 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004574
4575 // Try to fold constant and into select arguments.
4576 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004578 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004579 if (isa<PHINode>(Op0))
4580 if (Instruction *NV = FoldOpIntoPhi(I))
4581 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004582 }
4583
Chris Lattner4f637d42006-01-06 17:59:59 +00004584 Value *A = 0, *B = 0;
4585 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004586
4587 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4588 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4589 return ReplaceInstUsesWith(I, Op1);
4590 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4591 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4592 return ReplaceInstUsesWith(I, Op0);
4593
Chris Lattner6423d4c2006-07-10 20:25:24 +00004594 // (A | B) | C and A | (B | C) -> bswap if possible.
4595 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004596 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004597 match(Op1, m_Or(m_Value(), m_Value())) ||
4598 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4599 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004600 if (Instruction *BSwap = MatchBSwap(I))
4601 return BSwap;
4602 }
4603
Chris Lattner6e4c6492005-05-09 04:58:36 +00004604 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4605 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004606 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004607 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004608 InsertNewInstBefore(NOr, I);
4609 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004610 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004611 }
4612
4613 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4614 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004615 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004616 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004617 InsertNewInstBefore(NOr, I);
4618 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004619 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004620 }
4621
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004622 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004623 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004624 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4625 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004626 Value *V1 = 0, *V2 = 0, *V3 = 0;
4627 C1 = dyn_cast<ConstantInt>(C);
4628 C2 = dyn_cast<ConstantInt>(D);
4629 if (C1 && C2) { // (A & C1)|(B & C2)
4630 // If we have: ((V + N) & C1) | (V & C2)
4631 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4632 // replace with V+N.
4633 if (C1->getValue() == ~C2->getValue()) {
4634 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4635 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4636 // Add commutes, try both ways.
4637 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4638 return ReplaceInstUsesWith(I, A);
4639 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4640 return ReplaceInstUsesWith(I, A);
4641 }
4642 // Or commutes, try both ways.
4643 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4644 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4645 // Add commutes, try both ways.
4646 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4647 return ReplaceInstUsesWith(I, B);
4648 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4649 return ReplaceInstUsesWith(I, B);
4650 }
4651 }
Chris Lattner044e5332007-04-08 08:01:49 +00004652 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004653 }
4654
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004655 // Check to see if we have any common things being and'ed. If so, find the
4656 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004657 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4658 if (A == B) // (A & C)|(A & D) == A & (C|D)
4659 V1 = A, V2 = C, V3 = D;
4660 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4661 V1 = A, V2 = B, V3 = C;
4662 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4663 V1 = C, V2 = A, V3 = D;
4664 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4665 V1 = C, V2 = A, V3 = B;
4666
4667 if (V1) {
4668 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004669 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4670 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004671 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004672 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004673
Dan Gohman1975d032008-10-30 20:40:10 +00004674 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004675 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4676 return Match;
4677 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4678 return Match;
4679 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4680 return Match;
4681 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4682 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004683
Bill Wendlingb01865c2008-11-30 13:52:49 +00004684 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004685 if ((match(C, m_Not(m_Specific(D))) &&
4686 match(B, m_Not(m_Specific(A)))))
4687 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004688 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004689 if ((match(A, m_Not(m_Specific(D))) &&
4690 match(B, m_Not(m_Specific(C)))))
4691 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004692 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004693 if ((match(C, m_Not(m_Specific(B))) &&
4694 match(D, m_Not(m_Specific(A)))))
4695 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004696 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004697 if ((match(A, m_Not(m_Specific(B))) &&
4698 match(D, m_Not(m_Specific(C)))))
4699 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004700 }
Chris Lattnere511b742006-11-14 07:46:50 +00004701
4702 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004703 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4704 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4705 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004706 SI0->getOperand(1) == SI1->getOperand(1) &&
4707 (SI0->hasOneUse() || SI1->hasOneUse())) {
4708 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004709 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004710 SI1->getOperand(0),
4711 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004712 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004713 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004714 }
4715 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004716
Bill Wendlingb3833d12008-12-01 01:07:11 +00004717 // ((A|B)&1)|(B&-2) -> (A&1) | B
4718 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4719 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004720 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004721 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004722 }
4723 // (B&-2)|((A|B)&1) -> (A&1) | B
4724 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4725 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004726 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004727 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004728 }
4729
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004730 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4731 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004732 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004733 } else {
4734 A = 0;
4735 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004736 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004737 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4738 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004739 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004740
Misha Brukmancb6267b2004-07-30 12:50:08 +00004741 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004742 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004743 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004744 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004745 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004746 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004747 }
Chris Lattnera2881962003-02-18 19:28:33 +00004748
Reid Spencere4d87aa2006-12-23 06:05:41 +00004749 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4750 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4751 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004752 return R;
4753
Chris Lattner69d4ced2008-11-16 05:20:07 +00004754 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4755 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4756 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004757 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004758
4759 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004760 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004761 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004762 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004763 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4764 !isa<ICmpInst>(Op1C->getOperand(0))) {
4765 const Type *SrcTy = Op0C->getOperand(0)->getType();
4766 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4767 // Only do this if the casts both really cause code to be
4768 // generated.
4769 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4770 I.getType(), TD) &&
4771 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4772 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004774 Op1C->getOperand(0),
4775 I.getName());
4776 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004777 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004778 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004779 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004780 }
Chris Lattner99c65742007-10-24 05:38:08 +00004781 }
4782
4783
4784 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4785 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4786 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4787 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004788 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004789 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004790 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4791 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4792 // If either of the constants are nans, then the whole thing returns
4793 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004794 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004795 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4796
4797 // Otherwise, no need to compare the two constants, compare the
4798 // rest.
4799 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4800 RHS->getOperand(0));
4801 }
Evan Cheng40300622008-10-14 18:44:08 +00004802 } else {
4803 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4804 FCmpInst::Predicate Op0CC, Op1CC;
4805 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4806 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4807 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4808 // Swap RHS operands to match LHS.
4809 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4810 std::swap(Op1LHS, Op1RHS);
4811 }
4812 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4813 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4814 if (Op0CC == Op1CC)
4815 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4816 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4817 Op1CC == FCmpInst::FCMP_TRUE)
4818 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819 else if (Op0CC == FCmpInst::FCMP_FALSE)
4820 return ReplaceInstUsesWith(I, Op1);
4821 else if (Op1CC == FCmpInst::FCMP_FALSE)
4822 return ReplaceInstUsesWith(I, Op0);
4823 bool Op0Ordered;
4824 bool Op1Ordered;
4825 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4826 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4827 if (Op0Ordered == Op1Ordered) {
4828 // If both are ordered or unordered, return a new fcmp with
4829 // or'ed predicates.
4830 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4831 Op0LHS, Op0RHS);
4832 if (Instruction *I = dyn_cast<Instruction>(RV))
4833 return I;
4834 // Otherwise, it's a constant boolean value...
4835 return ReplaceInstUsesWith(I, RV);
4836 }
4837 }
4838 }
4839 }
Chris Lattner99c65742007-10-24 05:38:08 +00004840 }
4841 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004842
Chris Lattner7e708292002-06-25 16:13:24 +00004843 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004844}
4845
Dan Gohman844731a2008-05-13 00:00:25 +00004846namespace {
4847
Chris Lattnerc317d392004-02-16 01:20:27 +00004848// XorSelf - Implements: X ^ X --> 0
4849struct XorSelf {
4850 Value *RHS;
4851 XorSelf(Value *rhs) : RHS(rhs) {}
4852 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4853 Instruction *apply(BinaryOperator &Xor) const {
4854 return &Xor;
4855 }
4856};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004857
Dan Gohman844731a2008-05-13 00:00:25 +00004858}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004859
Chris Lattner7e708292002-06-25 16:13:24 +00004860Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004861 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004862 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004863
Evan Chengd34af782008-03-25 20:07:13 +00004864 if (isa<UndefValue>(Op1)) {
4865 if (isa<UndefValue>(Op0))
4866 // Handle undef ^ undef -> 0 special case. This is a common
4867 // idiom (misuse).
4868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004869 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004870 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004871
Chris Lattnerc317d392004-02-16 01:20:27 +00004872 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4873 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004874 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004875 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004876 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004877
4878 // See if we can simplify any instructions used by the instruction whose sole
4879 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004880 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004881 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004882 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004883 } else if (isa<ConstantAggregateZero>(Op1)) {
4884 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004885 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004886
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004887 // Is this a ~ operation?
4888 if (Value *NotOp = dyn_castNotVal(&I)) {
4889 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4890 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4891 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4892 if (Op0I->getOpcode() == Instruction::And ||
4893 Op0I->getOpcode() == Instruction::Or) {
4894 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4895 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4896 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004897 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004898 Op0I->getOperand(1)->getName()+".not");
4899 InsertNewInstBefore(NotY, I);
4900 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004901 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004902 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004904 }
4905 }
4906 }
4907 }
4908
4909
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004910 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004911 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004912 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004913 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004914 return new ICmpInst(ICI->getInversePredicate(),
4915 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004916
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004917 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4918 return new FCmpInst(FCI->getInversePredicate(),
4919 FCI->getOperand(0), FCI->getOperand(1));
4920 }
4921
Nick Lewycky517e1f52008-05-31 19:01:33 +00004922 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4923 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4924 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4925 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4926 Instruction::CastOps Opcode = Op0C->getOpcode();
4927 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4928 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4929 Op0C->getDestTy())) {
4930 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4931 CI->getOpcode(), CI->getInversePredicate(),
4932 CI->getOperand(0), CI->getOperand(1)), I);
4933 NewCI->takeName(CI);
4934 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4935 }
4936 }
4937 }
4938 }
4939 }
4940
Reid Spencere4d87aa2006-12-23 06:05:41 +00004941 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004942 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004943 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4944 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004945 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4946 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004947 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004948 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004949 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004950
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004951 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004952 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004953 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004954 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004955 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004956 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004957 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004958 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004959 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004960 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004961 // (X + C) ^ signbit -> (X + C + signbit)
4962 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004963 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004964
Chris Lattner7c4049c2004-01-12 19:35:11 +00004965 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004966 } else if (Op0I->getOpcode() == Instruction::Or) {
4967 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004968 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004969 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4970 // Anything in both C1 and C2 is known to be zero, remove it from
4971 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004972 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004973 NewRHS = ConstantExpr::getAnd(NewRHS,
4974 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004975 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004976 I.setOperand(0, Op0I->getOperand(0));
4977 I.setOperand(1, NewRHS);
4978 return &I;
4979 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004980 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004981 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004982 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004983
4984 // Try to fold constant and into select arguments.
4985 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004986 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004987 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004988 if (isa<PHINode>(Op0))
4989 if (Instruction *NV = FoldOpIntoPhi(I))
4990 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004991 }
4992
Chris Lattner8d969642003-03-10 23:06:50 +00004993 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004994 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004995 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004996
Chris Lattner8d969642003-03-10 23:06:50 +00004997 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004998 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004999 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005000
Chris Lattner318bf792007-03-18 22:51:34 +00005001
5002 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5003 if (Op1I) {
5004 Value *A, *B;
5005 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5006 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005007 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005008 I.swapOperands();
5009 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005010 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005011 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005012 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005013 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005014 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5015 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5016 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5017 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005018 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005019 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005020 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005021 std::swap(A, B);
5022 }
Chris Lattner318bf792007-03-18 22:51:34 +00005023 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005024 I.swapOperands(); // Simplified below.
5025 std::swap(Op0, Op1);
5026 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005027 }
Chris Lattner318bf792007-03-18 22:51:34 +00005028 }
5029
5030 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5031 if (Op0I) {
5032 Value *A, *B;
5033 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5034 if (A == Op1) // (B|A)^B == (A|B)^B
5035 std::swap(A, B);
5036 if (B == Op1) { // (A|B)^B == A & ~B
5037 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005038 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5039 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005040 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005041 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5042 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5043 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5044 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005045 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5046 if (A == Op1) // (A&B)^A -> (B&A)^A
5047 std::swap(A, B);
5048 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005049 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005050 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005051 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5052 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005053 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005054 }
Chris Lattner318bf792007-03-18 22:51:34 +00005055 }
5056
5057 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5058 if (Op0I && Op1I && Op0I->isShift() &&
5059 Op0I->getOpcode() == Op1I->getOpcode() &&
5060 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5061 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5062 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005064 Op1I->getOperand(0),
5065 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005066 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005067 Op1I->getOperand(1));
5068 }
5069
5070 if (Op0I && Op1I) {
5071 Value *A, *B, *C, *D;
5072 // (A & B)^(A | B) -> A ^ B
5073 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5074 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5075 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005076 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005077 }
5078 // (A | B)^(A & B) -> A ^ B
5079 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5080 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5081 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005082 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005083 }
5084
5085 // (A & B)^(C & D)
5086 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5087 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5088 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5089 // (X & Y)^(X & Y) -> (Y^Z) & X
5090 Value *X = 0, *Y = 0, *Z = 0;
5091 if (A == C)
5092 X = A, Y = B, Z = D;
5093 else if (A == D)
5094 X = A, Y = B, Z = C;
5095 else if (B == C)
5096 X = B, Y = A, Z = D;
5097 else if (B == D)
5098 X = B, Y = A, Z = C;
5099
5100 if (X) {
5101 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005102 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5103 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005104 }
5105 }
5106 }
5107
Reid Spencere4d87aa2006-12-23 06:05:41 +00005108 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5109 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5110 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005111 return R;
5112
Chris Lattner6fc205f2006-05-05 06:39:07 +00005113 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005114 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005115 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005116 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5117 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005118 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005119 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005120 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5121 I.getType(), TD) &&
5122 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5123 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005124 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005125 Op1C->getOperand(0),
5126 I.getName());
5127 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005129 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005130 }
Chris Lattner99c65742007-10-24 05:38:08 +00005131 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005132
Chris Lattner7e708292002-06-25 16:13:24 +00005133 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005134}
5135
Chris Lattnera96879a2004-09-29 17:40:11 +00005136/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5137/// overflowed for this type.
5138static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005139 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005140 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005141
Reid Spencere4e40032007-03-21 23:19:50 +00005142 if (IsSigned)
5143 if (In2->getValue().isNegative())
5144 return Result->getValue().sgt(In1->getValue());
5145 else
5146 return Result->getValue().slt(In1->getValue());
5147 else
5148 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005149}
5150
Dan Gohman1df3fd62008-09-10 23:30:57 +00005151/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5152/// overflowed for this type.
5153static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5154 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005155 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005156
5157 if (IsSigned)
5158 if (In2->getValue().isNegative())
5159 return Result->getValue().slt(In1->getValue());
5160 else
5161 return Result->getValue().sgt(In1->getValue());
5162 else
5163 return Result->getValue().ugt(In1->getValue());
5164}
5165
Chris Lattner574da9b2005-01-13 20:14:25 +00005166/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5167/// code necessary to compute the offset from the base pointer (without adding
5168/// in the base pointer). Return the result as a signed integer of intptr size.
5169static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5170 TargetData &TD = IC.getTargetData();
5171 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 const Type *IntPtrTy = TD.getIntPtrType();
5173 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005174
5175 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005176 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005177 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005178
Gabor Greif177dd3f2008-06-12 21:37:33 +00005179 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5180 ++i, ++GTI) {
5181 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005182 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005183 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5184 if (OpC->isZero()) continue;
5185
5186 // Handle a struct index, which adds its field offset to the pointer.
5187 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5188 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5189
5190 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5191 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005192 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005193 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005194 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005195 ConstantInt::get(IntPtrTy, Size),
5196 GEP->getName()+".offs"), I);
5197 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005198 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005199
5200 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5201 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5202 Scale = ConstantExpr::getMul(OC, Scale);
5203 if (Constant *RC = dyn_cast<Constant>(Result))
5204 Result = ConstantExpr::getAdd(RC, Scale);
5205 else {
5206 // Emit an add instruction.
5207 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005208 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005209 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005210 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005211 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005212 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005213 // Convert to correct type.
5214 if (Op->getType() != IntPtrTy) {
5215 if (Constant *OpC = dyn_cast<Constant>(Op))
5216 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5217 else
5218 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5219 Op->getName()+".c"), I);
5220 }
5221 if (Size != 1) {
5222 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5223 if (Constant *OpC = dyn_cast<Constant>(Op))
5224 Op = ConstantExpr::getMul(OpC, Scale);
5225 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005226 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005227 GEP->getName()+".idx"), I);
5228 }
5229
5230 // Emit an add instruction.
5231 if (isa<Constant>(Op) && isa<Constant>(Result))
5232 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5233 cast<Constant>(Result));
5234 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005235 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005236 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005237 }
5238 return Result;
5239}
5240
Chris Lattner10c0d912008-04-22 02:53:33 +00005241
5242/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5243/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5244/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5245/// complex, and scales are involved. The above expression would also be legal
5246/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5247/// later form is less amenable to optimization though, and we are allowed to
5248/// generate the first by knowing that pointer arithmetic doesn't overflow.
5249///
5250/// If we can't emit an optimized form for this expression, this returns null.
5251///
5252static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5253 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005254 TargetData &TD = IC.getTargetData();
5255 gep_type_iterator GTI = gep_type_begin(GEP);
5256
5257 // Check to see if this gep only has a single variable index. If so, and if
5258 // any constant indices are a multiple of its scale, then we can compute this
5259 // in terms of the scale of the variable index. For example, if the GEP
5260 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5261 // because the expression will cross zero at the same point.
5262 unsigned i, e = GEP->getNumOperands();
5263 int64_t Offset = 0;
5264 for (i = 1; i != e; ++i, ++GTI) {
5265 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5266 // Compute the aggregate offset of constant indices.
5267 if (CI->isZero()) continue;
5268
5269 // Handle a struct index, which adds its field offset to the pointer.
5270 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5271 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5272 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005273 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005274 Offset += Size*CI->getSExtValue();
5275 }
5276 } else {
5277 // Found our variable index.
5278 break;
5279 }
5280 }
5281
5282 // If there are no variable indices, we must have a constant offset, just
5283 // evaluate it the general way.
5284 if (i == e) return 0;
5285
5286 Value *VariableIdx = GEP->getOperand(i);
5287 // Determine the scale factor of the variable element. For example, this is
5288 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005289 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005290
5291 // Verify that there are no other variable indices. If so, emit the hard way.
5292 for (++i, ++GTI; i != e; ++i, ++GTI) {
5293 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5294 if (!CI) return 0;
5295
5296 // Compute the aggregate offset of constant indices.
5297 if (CI->isZero()) continue;
5298
5299 // Handle a struct index, which adds its field offset to the pointer.
5300 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5301 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5302 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005303 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005304 Offset += Size*CI->getSExtValue();
5305 }
5306 }
5307
5308 // Okay, we know we have a single variable index, which must be a
5309 // pointer/array/vector index. If there is no offset, life is simple, return
5310 // the index.
5311 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5312 if (Offset == 0) {
5313 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5314 // we don't need to bother extending: the extension won't affect where the
5315 // computation crosses zero.
5316 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5317 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5318 VariableIdx->getNameStart(), &I);
5319 return VariableIdx;
5320 }
5321
5322 // Otherwise, there is an index. The computation we will do will be modulo
5323 // the pointer size, so get it.
5324 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5325
5326 Offset &= PtrSizeMask;
5327 VariableScale &= PtrSizeMask;
5328
5329 // To do this transformation, any constant index must be a multiple of the
5330 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5331 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5332 // multiple of the variable scale.
5333 int64_t NewOffs = Offset / (int64_t)VariableScale;
5334 if (Offset != NewOffs*(int64_t)VariableScale)
5335 return 0;
5336
5337 // Okay, we can do this evaluation. Start by converting the index to intptr.
5338 const Type *IntPtrTy = TD.getIntPtrType();
5339 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005340 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005341 true /*SExt*/,
5342 VariableIdx->getNameStart(), &I);
5343 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005344 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005345}
5346
5347
Reid Spencere4d87aa2006-12-23 06:05:41 +00005348/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005349/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5351 ICmpInst::Predicate Cond,
5352 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005353 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005354
Chris Lattner10c0d912008-04-22 02:53:33 +00005355 // Look through bitcasts.
5356 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5357 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005358
Chris Lattner574da9b2005-01-13 20:14:25 +00005359 Value *PtrBase = GEPLHS->getOperand(0);
5360 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005361 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005362 // This transformation (ignoring the base and scales) is valid because we
5363 // know pointers can't overflow. See if we can output an optimized form.
5364 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5365
5366 // If not, synthesize the offset the hard way.
5367 if (Offset == 0)
5368 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005369 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5370 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005371 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005372 // If the base pointers are different, but the indices are the same, just
5373 // compare the base pointer.
5374 if (PtrBase != GEPRHS->getOperand(0)) {
5375 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005376 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005377 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005378 if (IndicesTheSame)
5379 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5380 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5381 IndicesTheSame = false;
5382 break;
5383 }
5384
5385 // If all indices are the same, just compare the base pointers.
5386 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5388 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005389
5390 // Otherwise, the base pointers are different and the indices are
5391 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005392 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005393 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005394
Chris Lattnere9d782b2005-01-13 22:25:21 +00005395 // If one of the GEPs has all zero indices, recurse.
5396 bool AllZeros = true;
5397 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5398 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5399 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5400 AllZeros = false;
5401 break;
5402 }
5403 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005404 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5405 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005406
5407 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005408 AllZeros = true;
5409 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5410 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5411 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5412 AllZeros = false;
5413 break;
5414 }
5415 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005416 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005417
Chris Lattner4401c9c2005-01-14 00:20:05 +00005418 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5419 // If the GEPs only differ by one index, compare it.
5420 unsigned NumDifferences = 0; // Keep track of # differences.
5421 unsigned DiffOperand = 0; // The operand that differs.
5422 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5423 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005424 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5425 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005426 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005427 NumDifferences = 2;
5428 break;
5429 } else {
5430 if (NumDifferences++) break;
5431 DiffOperand = i;
5432 }
5433 }
5434
5435 if (NumDifferences == 0) // SAME GEP?
5436 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005437 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005438 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005439
Chris Lattner4401c9c2005-01-14 00:20:05 +00005440 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005441 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5442 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 // Make sure we do a signed comparison here.
5444 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005445 }
5446 }
5447
Reid Spencere4d87aa2006-12-23 06:05:41 +00005448 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005449 // the result to fold to a constant!
5450 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5451 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5452 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5453 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5454 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005455 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005456 }
5457 }
5458 return 0;
5459}
5460
Chris Lattnera5406232008-05-19 20:18:56 +00005461/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5462///
5463Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5464 Instruction *LHSI,
5465 Constant *RHSC) {
5466 if (!isa<ConstantFP>(RHSC)) return 0;
5467 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5468
5469 // Get the width of the mantissa. We don't want to hack on conversions that
5470 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005471 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005472 if (MantissaWidth == -1) return 0; // Unknown.
5473
5474 // Check to see that the input is converted from an integer type that is small
5475 // enough that preserves all bits. TODO: check here for "known" sign bits.
5476 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5477 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5478
5479 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005480 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5481 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005482 ++InputSize;
5483
5484 // If the conversion would lose info, don't hack on this.
5485 if ((int)InputSize > MantissaWidth)
5486 return 0;
5487
5488 // Otherwise, we can potentially simplify the comparison. We know that it
5489 // will always come through as an integer value and we know the constant is
5490 // not a NAN (it would have been previously simplified).
5491 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5492
5493 ICmpInst::Predicate Pred;
5494 switch (I.getPredicate()) {
5495 default: assert(0 && "Unexpected predicate!");
5496 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005497 case FCmpInst::FCMP_OEQ:
5498 Pred = ICmpInst::ICMP_EQ;
5499 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005500 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005501 case FCmpInst::FCMP_OGT:
5502 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5503 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005504 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005505 case FCmpInst::FCMP_OGE:
5506 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5507 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005508 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005509 case FCmpInst::FCMP_OLT:
5510 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5511 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005512 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005513 case FCmpInst::FCMP_OLE:
5514 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5515 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005516 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005517 case FCmpInst::FCMP_ONE:
5518 Pred = ICmpInst::ICMP_NE;
5519 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005520 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005521 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005522 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005523 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005524 }
5525
5526 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5527
5528 // Now we know that the APFloat is a normal number, zero or inf.
5529
Chris Lattner85162782008-05-20 03:50:52 +00005530 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005531 // comparing an i8 to 300.0.
5532 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5533
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005534 if (!LHSUnsigned) {
5535 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5536 // and large values.
5537 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5538 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5539 APFloat::rmNearestTiesToEven);
5540 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5541 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5542 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005543 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5544 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005545 }
5546 } else {
5547 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5548 // +INF and large values.
5549 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5550 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5551 APFloat::rmNearestTiesToEven);
5552 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5553 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5554 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005555 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5556 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005557 }
Chris Lattnera5406232008-05-19 20:18:56 +00005558 }
5559
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005560 if (!LHSUnsigned) {
5561 // See if the RHS value is < SignedMin.
5562 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5563 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5564 APFloat::rmNearestTiesToEven);
5565 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5566 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5567 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005568 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5569 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005570 }
Chris Lattnera5406232008-05-19 20:18:56 +00005571 }
5572
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005573 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5574 // [0, UMAX], but it may still be fractional. See if it is fractional by
5575 // casting the FP value to the integer value and back, checking for equality.
5576 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005577 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5578 if (!RHS.isZero() &&
5579 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005580 // If we had a comparison against a fractional value, we have to adjust the
5581 // compare predicate and sometimes the value. RHSC is rounded towards zero
5582 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005583 switch (Pred) {
5584 default: assert(0 && "Unexpected integer comparison!");
5585 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005587 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005588 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005589 case ICmpInst::ICMP_ULE:
5590 // (float)int <= 4.4 --> int <= 4
5591 // (float)int <= -4.4 --> false
5592 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005594 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005595 case ICmpInst::ICMP_SLE:
5596 // (float)int <= 4.4 --> int <= 4
5597 // (float)int <= -4.4 --> int < -4
5598 if (RHS.isNegative())
5599 Pred = ICmpInst::ICMP_SLT;
5600 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005601 case ICmpInst::ICMP_ULT:
5602 // (float)int < -4.4 --> false
5603 // (float)int < 4.4 --> int <= 4
5604 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005605 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005606 Pred = ICmpInst::ICMP_ULE;
5607 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005608 case ICmpInst::ICMP_SLT:
5609 // (float)int < -4.4 --> int < -4
5610 // (float)int < 4.4 --> int <= 4
5611 if (!RHS.isNegative())
5612 Pred = ICmpInst::ICMP_SLE;
5613 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005614 case ICmpInst::ICMP_UGT:
5615 // (float)int > 4.4 --> int > 4
5616 // (float)int > -4.4 --> true
5617 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005618 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005619 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005620 case ICmpInst::ICMP_SGT:
5621 // (float)int > 4.4 --> int > 4
5622 // (float)int > -4.4 --> int >= -4
5623 if (RHS.isNegative())
5624 Pred = ICmpInst::ICMP_SGE;
5625 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005626 case ICmpInst::ICMP_UGE:
5627 // (float)int >= -4.4 --> true
5628 // (float)int >= 4.4 --> int > 4
5629 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005630 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005631 Pred = ICmpInst::ICMP_UGT;
5632 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005633 case ICmpInst::ICMP_SGE:
5634 // (float)int >= -4.4 --> int >= -4
5635 // (float)int >= 4.4 --> int > 4
5636 if (!RHS.isNegative())
5637 Pred = ICmpInst::ICMP_SGT;
5638 break;
5639 }
5640 }
5641
5642 // Lower this FP comparison into an appropriate integer version of the
5643 // comparison.
5644 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5645}
5646
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5648 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005650
Chris Lattner58e97462007-01-14 19:42:17 +00005651 // Fold trivial predicates.
5652 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005653 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005654 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005655 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005656
5657 // Simplify 'fcmp pred X, X'
5658 if (Op0 == Op1) {
5659 switch (I.getPredicate()) {
5660 default: assert(0 && "Unknown predicate!");
5661 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5662 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5663 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005664 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005665 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5666 case FCmpInst::FCMP_OLT: // True if ordered and less than
5667 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005668 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005669
5670 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5671 case FCmpInst::FCMP_ULT: // True if unordered or less than
5672 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5673 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5674 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5675 I.setPredicate(FCmpInst::FCMP_UNO);
5676 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5677 return &I;
5678
5679 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5680 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5681 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5682 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5683 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5684 I.setPredicate(FCmpInst::FCMP_ORD);
5685 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5686 return &I;
5687 }
5688 }
5689
Reid Spencere4d87aa2006-12-23 06:05:41 +00005690 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005691 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005692
Reid Spencere4d87aa2006-12-23 06:05:41 +00005693 // Handle fcmp with constant RHS
5694 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005695 // If the constant is a nan, see if we can fold the comparison based on it.
5696 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5697 if (CFP->getValueAPF().isNaN()) {
5698 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005699 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005700 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5701 "Comparison must be either ordered or unordered!");
5702 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005703 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005704 }
5705 }
5706
Reid Spencere4d87aa2006-12-23 06:05:41 +00005707 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5708 switch (LHSI->getOpcode()) {
5709 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005710 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5711 // block. If in the same block, we're encouraging jump threading. If
5712 // not, we are just pessimizing the code by making an i1 phi.
5713 if (LHSI->getParent() == I.getParent())
5714 if (Instruction *NV = FoldOpIntoPhi(I))
5715 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005716 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005717 case Instruction::SIToFP:
5718 case Instruction::UIToFP:
5719 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5720 return NV;
5721 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005722 case Instruction::Select:
5723 // If either operand of the select is a constant, we can fold the
5724 // comparison into the select arms, which will cause one to be
5725 // constant folded and the select turned into a bitwise or.
5726 Value *Op1 = 0, *Op2 = 0;
5727 if (LHSI->hasOneUse()) {
5728 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5729 // Fold the known value into the constant operand.
5730 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5731 // Insert a new FCmp of the other select operand.
5732 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5733 LHSI->getOperand(2), RHSC,
5734 I.getName()), I);
5735 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5736 // Fold the known value into the constant operand.
5737 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5738 // Insert a new FCmp of the other select operand.
5739 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5740 LHSI->getOperand(1), RHSC,
5741 I.getName()), I);
5742 }
5743 }
5744
5745 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005746 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005747 break;
5748 }
5749 }
5750
5751 return Changed ? &I : 0;
5752}
5753
5754Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5755 bool Changed = SimplifyCompare(I);
5756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5757 const Type *Ty = Op0->getType();
5758
5759 // icmp X, X
5760 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005761 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005762 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005763
5764 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005765 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005766
Reid Spencere4d87aa2006-12-23 06:05:41 +00005767 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005768 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005769 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5770 isa<ConstantPointerNull>(Op0)) &&
5771 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005772 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005773 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005774 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005775
Reid Spencere4d87aa2006-12-23 06:05:41 +00005776 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005777 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005778 switch (I.getPredicate()) {
5779 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005780 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005781 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005782 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005783 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005784 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005785 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005786 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005787
Reid Spencere4d87aa2006-12-23 06:05:41 +00005788 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005789 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005790 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005791 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005792 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005793 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005794 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005795 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005796 case ICmpInst::ICMP_SGT:
5797 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005798 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005799 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5800 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5801 InsertNewInstBefore(Not, I);
5802 return BinaryOperator::CreateAnd(Not, Op0);
5803 }
5804 case ICmpInst::ICMP_UGE:
5805 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5806 // FALL THROUGH
5807 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005808 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005809 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005810 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005811 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005812 case ICmpInst::ICMP_SGE:
5813 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5814 // FALL THROUGH
5815 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5816 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5817 InsertNewInstBefore(Not, I);
5818 return BinaryOperator::CreateOr(Not, Op0);
5819 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005820 }
Chris Lattner8b170942002-08-09 23:47:40 +00005821 }
5822
Dan Gohman81b28ce2008-09-16 18:46:06 +00005823 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005824 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005825 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005826
Chris Lattnerb6566012008-01-05 01:18:20 +00005827 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5828 if (I.isEquality() && CI->isNullValue() &&
5829 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5830 // (icmp cond A B) if cond is equality
5831 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005832 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005833
Dan Gohman81b28ce2008-09-16 18:46:06 +00005834 // If we have an icmp le or icmp ge instruction, turn it into the
5835 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5836 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005837 switch (I.getPredicate()) {
5838 default: break;
5839 case ICmpInst::ICMP_ULE:
5840 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5841 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5843 case ICmpInst::ICMP_SLE:
5844 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5845 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5847 case ICmpInst::ICMP_UGE:
5848 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5849 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5851 case ICmpInst::ICMP_SGE:
5852 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5853 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5854 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5855 }
5856
Chris Lattner183661e2008-07-11 05:40:05 +00005857 // See if we can fold the comparison based on range information we can get
5858 // by checking whether bits are known to be zero or one in the input.
5859 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5860 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5861
5862 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005863 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005864 bool UnusedBit;
5865 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5866
Chris Lattner886ab6c2009-01-31 08:15:18 +00005867 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005868 isSignBit ? APInt::getSignBit(BitWidth)
5869 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005870 KnownZero, KnownOne, 0))
5871 return &I;
5872
5873 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005874 // in. Compute the Min, Max and RHS values based on the known bits. For the
5875 // EQ and NE we use unsigned values.
5876 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005877 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5878 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5879 else
5880 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5881
Chris Lattner183661e2008-07-11 05:40:05 +00005882 // If Min and Max are known to be the same, then SimplifyDemandedBits
5883 // figured out that the LHS is a constant. Just constant fold this now so
5884 // that code below can assume that Min != Max.
5885 if (Min == Max)
5886 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5887 ConstantInt::get(Min),
5888 CI));
5889
5890 // Based on the range information we know about the LHS, see if we can
5891 // simplify this comparison. For example, (x&4) < 8 is always true.
5892 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005893 switch (I.getPredicate()) { // LE/GE have been folded already.
5894 default: assert(0 && "Unknown icmp opcode!");
5895 case ICmpInst::ICMP_EQ:
5896 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5897 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5898 break;
5899 case ICmpInst::ICMP_NE:
5900 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5901 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5902 break;
5903 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005904 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005905 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005906 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005907 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005908 if (RHSVal == Max) // A <u MAX -> A != MAX
5909 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5910 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5911 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5912
5913 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5914 if (CI->isMinValue(true))
5915 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5916 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005917 break;
5918 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005919 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005920 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005921 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005922 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005923
5924 if (RHSVal == Min) // A >u MIN -> A != MIN
5925 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5926 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5927 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5928
5929 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5930 if (CI->isMaxValue(true))
5931 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5932 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005933 break;
5934 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005935 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005936 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005937 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005939 if (RHSVal == Max) // A <s MAX -> A != MAX
5940 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005941 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005942 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005943 break;
5944 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005945 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005946 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005947 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005949
5950 if (RHSVal == Min) // A >s MIN -> A != MIN
5951 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5952 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5953 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005954 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005955 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005956 }
5957
5958 // Test if the ICmpInst instruction is used exclusively by a select as
5959 // part of a minimum or maximum operation. If so, refrain from doing
5960 // any other folding. This helps out other analyses which understand
5961 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5962 // and CodeGen. And in this case, at least one of the comparison
5963 // operands has at least one user besides the compare (the select),
5964 // which would often largely negate the benefit of folding anyway.
5965 if (I.hasOneUse())
5966 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5967 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5968 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5969 return 0;
5970
5971 // See if we are doing a comparison between a constant and an instruction that
5972 // can be folded into the comparison.
5973 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005975 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005977 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005978 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5979 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005980 }
5981
Chris Lattner01deb9d2007-04-03 17:43:25 +00005982 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005983 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5984 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5985 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005986 case Instruction::GetElementPtr:
5987 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005989 bool isAllZeros = true;
5990 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5991 if (!isa<Constant>(LHSI->getOperand(i)) ||
5992 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5993 isAllZeros = false;
5994 break;
5995 }
5996 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005998 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5999 }
6000 break;
6001
Chris Lattner6970b662005-04-23 15:31:55 +00006002 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006003 // Only fold icmp into the PHI if the phi and fcmp are in the same
6004 // block. If in the same block, we're encouraging jump threading. If
6005 // not, we are just pessimizing the code by making an i1 phi.
6006 if (LHSI->getParent() == I.getParent())
6007 if (Instruction *NV = FoldOpIntoPhi(I))
6008 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006009 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006010 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006011 // If either operand of the select is a constant, we can fold the
6012 // comparison into the select arms, which will cause one to be
6013 // constant folded and the select turned into a bitwise or.
6014 Value *Op1 = 0, *Op2 = 0;
6015 if (LHSI->hasOneUse()) {
6016 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6017 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6019 // Insert a new ICmp of the other select operand.
6020 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6021 LHSI->getOperand(2), RHSC,
6022 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006023 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6026 // Insert a new ICmp of the other select operand.
6027 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6028 LHSI->getOperand(1), RHSC,
6029 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006030 }
6031 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006032
Chris Lattner6970b662005-04-23 15:31:55 +00006033 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006034 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006035 break;
6036 }
Chris Lattner4802d902007-04-06 18:57:34 +00006037 case Instruction::Malloc:
6038 // If we have (malloc != null), and if the malloc has a single use, we
6039 // can assume it is successful and remove the malloc.
6040 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6041 AddToWorkList(LHSI);
6042 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006043 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006044 }
6045 break;
6046 }
Chris Lattner6970b662005-04-23 15:31:55 +00006047 }
6048
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006050 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006051 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006052 return NI;
6053 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6055 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006056 return NI;
6057
Reid Spencere4d87aa2006-12-23 06:05:41 +00006058 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006059 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6060 // now.
6061 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6062 if (isa<PointerType>(Op0->getType()) &&
6063 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006064 // We keep moving the cast from the left operand over to the right
6065 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006066 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006067
Chris Lattner57d86372007-01-06 01:45:59 +00006068 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6069 // so eliminate it as well.
6070 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6071 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006072
Chris Lattnerde90b762003-11-03 04:25:02 +00006073 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006074 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006075 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006076 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006077 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006079 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006080 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006081 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006083 }
Chris Lattner57d86372007-01-06 01:45:59 +00006084 }
6085
6086 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006087 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006088 // This comes up when you have code like
6089 // int X = A < B;
6090 // if (X) ...
6091 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006092 // with a constant or another cast from the same type.
6093 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006094 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006095 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006096 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006097
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006098 // See if it's the same type of instruction on the left and right.
6099 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6100 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006101 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006102 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006103 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006104 default: break;
6105 case Instruction::Add:
6106 case Instruction::Sub:
6107 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006108 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006109 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6110 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006111 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6113 if (CI->getValue().isSignBit()) {
6114 ICmpInst::Predicate Pred = I.isSignedPredicate()
6115 ? I.getUnsignedPredicate()
6116 : I.getSignedPredicate();
6117 return new ICmpInst(Pred, Op0I->getOperand(0),
6118 Op1I->getOperand(0));
6119 }
6120
6121 if (CI->getValue().isMaxSignedValue()) {
6122 ICmpInst::Predicate Pred = I.isSignedPredicate()
6123 ? I.getUnsignedPredicate()
6124 : I.getSignedPredicate();
6125 Pred = I.getSwappedPredicate(Pred);
6126 return new ICmpInst(Pred, Op0I->getOperand(0),
6127 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006128 }
6129 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006130 break;
6131 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006132 if (!I.isEquality())
6133 break;
6134
Nick Lewycky5d52c452008-08-21 05:56:10 +00006135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6136 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6137 // Mask = -1 >> count-trailing-zeros(Cst).
6138 if (!CI->isZero() && !CI->isOne()) {
6139 const APInt &AP = CI->getValue();
6140 ConstantInt *Mask = ConstantInt::get(
6141 APInt::getLowBitsSet(AP.getBitWidth(),
6142 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006143 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006144 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6145 Mask);
6146 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6147 Mask);
6148 InsertNewInstBefore(And1, I);
6149 InsertNewInstBefore(And2, I);
6150 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006151 }
6152 }
6153 break;
6154 }
6155 }
6156 }
6157 }
6158
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006159 // ~x < ~y --> y < x
6160 { Value *A, *B;
6161 if (match(Op0, m_Not(m_Value(A))) &&
6162 match(Op1, m_Not(m_Value(B))))
6163 return new ICmpInst(I.getPredicate(), B, A);
6164 }
6165
Chris Lattner65b72ba2006-09-18 04:22:48 +00006166 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006167 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006168
6169 // -x == -y --> x == y
6170 if (match(Op0, m_Neg(m_Value(A))) &&
6171 match(Op1, m_Neg(m_Value(B))))
6172 return new ICmpInst(I.getPredicate(), A, B);
6173
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006174 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6175 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6176 Value *OtherVal = A == Op1 ? B : A;
6177 return new ICmpInst(I.getPredicate(), OtherVal,
6178 Constant::getNullValue(A->getType()));
6179 }
6180
6181 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6182 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006183 ConstantInt *C1, *C2;
6184 if (match(B, m_ConstantInt(C1)) &&
6185 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6186 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6187 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6188 return new ICmpInst(I.getPredicate(), A,
6189 InsertNewInstBefore(Xor, I));
6190 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006191
6192 // A^B == A^D -> B == D
6193 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6194 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6195 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6196 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6197 }
6198 }
6199
6200 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6201 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006202 // A == (A^B) -> B == 0
6203 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006204 return new ICmpInst(I.getPredicate(), OtherVal,
6205 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006206 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006207
6208 // (A-B) == A -> B == 0
6209 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6210 return new ICmpInst(I.getPredicate(), B,
6211 Constant::getNullValue(B->getType()));
6212
6213 // A == (A-B) -> B == 0
6214 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006215 return new ICmpInst(I.getPredicate(), B,
6216 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006217
Chris Lattner9c2328e2006-11-14 06:06:06 +00006218 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6219 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6220 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6221 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6222 Value *X = 0, *Y = 0, *Z = 0;
6223
6224 if (A == C) {
6225 X = B; Y = D; Z = A;
6226 } else if (A == D) {
6227 X = B; Y = C; Z = A;
6228 } else if (B == C) {
6229 X = A; Y = D; Z = B;
6230 } else if (B == D) {
6231 X = A; Y = C; Z = B;
6232 }
6233
6234 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006235 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6236 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006237 I.setOperand(0, Op1);
6238 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6239 return &I;
6240 }
6241 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006242 }
Chris Lattner7e708292002-06-25 16:13:24 +00006243 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006244}
6245
Chris Lattner562ef782007-06-20 23:46:26 +00006246
6247/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6248/// and CmpRHS are both known to be integer constants.
6249Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6250 ConstantInt *DivRHS) {
6251 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6252 const APInt &CmpRHSV = CmpRHS->getValue();
6253
6254 // FIXME: If the operand types don't match the type of the divide
6255 // then don't attempt this transform. The code below doesn't have the
6256 // logic to deal with a signed divide and an unsigned compare (and
6257 // vice versa). This is because (x /s C1) <s C2 produces different
6258 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6259 // (x /u C1) <u C2. Simply casting the operands and result won't
6260 // work. :( The if statement below tests that condition and bails
6261 // if it finds it.
6262 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6263 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6264 return 0;
6265 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006266 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006267 if (DivIsSigned && DivRHS->isAllOnesValue())
6268 return 0; // The overflow computation also screws up here
6269 if (DivRHS->isOne())
6270 return 0; // Not worth bothering, and eliminates some funny cases
6271 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006272
6273 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6274 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6275 // C2 (CI). By solving for X we can turn this into a range check
6276 // instead of computing a divide.
6277 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6278
6279 // Determine if the product overflows by seeing if the product is
6280 // not equal to the divide. Make sure we do the same kind of divide
6281 // as in the LHS instruction that we're folding.
6282 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6283 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6284
6285 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006286 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006287
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 // Figure out the interval that is being checked. For example, a comparison
6289 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6290 // Compute this interval based on the constants involved and the signedness of
6291 // the compare/divide. This computes a half-open interval, keeping track of
6292 // whether either value in the interval overflows. After analysis each
6293 // overflow variable is set to 0 if it's corresponding bound variable is valid
6294 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6295 int LoOverflow = 0, HiOverflow = 0;
6296 ConstantInt *LoBound = 0, *HiBound = 0;
6297
Chris Lattner562ef782007-06-20 23:46:26 +00006298 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006299 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006300 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006301 HiOverflow = LoOverflow = ProdOV;
6302 if (!HiOverflow)
6303 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006304 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006305 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006306 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006307 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6308 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006309 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006310 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6311 HiOverflow = LoOverflow = ProdOV;
6312 if (!HiOverflow)
6313 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006314 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006315 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006316 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006317 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6318 if (!LoOverflow) {
6319 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6320 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6321 true) ? -1 : 0;
6322 }
Chris Lattner562ef782007-06-20 23:46:26 +00006323 }
Dan Gohman76491272008-02-13 22:09:18 +00006324 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006325 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006326 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006327 LoBound = AddOne(DivRHS);
6328 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006329 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6330 HiOverflow = 1; // [INTMIN+1, overflow)
6331 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6332 }
Dan Gohman76491272008-02-13 22:09:18 +00006333 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006334 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006335 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006336 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006337 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006338 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006339 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006340 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6341 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006342 if (!HiOverflow)
6343 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006344 }
6345
Chris Lattner1dbfd482007-06-21 18:11:19 +00006346 // Dividing by a negative swaps the condition. LT <-> GT
6347 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006348 }
6349
6350 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006351 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006352 default: assert(0 && "Unhandled icmp opcode!");
6353 case ICmpInst::ICMP_EQ:
6354 if (LoOverflow && HiOverflow)
6355 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6356 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006357 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006358 ICmpInst::ICMP_UGE, X, LoBound);
6359 else if (LoOverflow)
6360 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6361 ICmpInst::ICMP_ULT, X, HiBound);
6362 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006363 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006364 case ICmpInst::ICMP_NE:
6365 if (LoOverflow && HiOverflow)
6366 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6367 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006368 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006369 ICmpInst::ICMP_ULT, X, LoBound);
6370 else if (LoOverflow)
6371 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6372 ICmpInst::ICMP_UGE, X, HiBound);
6373 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006374 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006375 case ICmpInst::ICMP_ULT:
6376 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006377 if (LoOverflow == +1) // Low bound is greater than input range.
6378 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6379 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006380 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006381 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006382 case ICmpInst::ICMP_UGT:
6383 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006384 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006385 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006386 else if (HiOverflow == -1) // High bound less than input range.
6387 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6388 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006389 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6390 else
6391 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6392 }
6393}
6394
6395
Chris Lattner01deb9d2007-04-03 17:43:25 +00006396/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6397///
6398Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6399 Instruction *LHSI,
6400 ConstantInt *RHS) {
6401 const APInt &RHSV = RHS->getValue();
6402
6403 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006404 case Instruction::Trunc:
6405 if (ICI.isEquality() && LHSI->hasOneUse()) {
6406 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6407 // of the high bits truncated out of x are known.
6408 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6409 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6410 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6411 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6412 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6413
6414 // If all the high bits are known, we can do this xform.
6415 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6416 // Pull in the high bits from known-ones set.
6417 APInt NewRHS(RHS->getValue());
6418 NewRHS.zext(SrcBits);
6419 NewRHS |= KnownOne;
6420 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6421 ConstantInt::get(NewRHS));
6422 }
6423 }
6424 break;
6425
Duncan Sands0091bf22007-04-04 06:42:45 +00006426 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006427 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6428 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6429 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006430 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6431 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006432 Value *CompareVal = LHSI->getOperand(0);
6433
6434 // If the sign bit of the XorCST is not set, there is no change to
6435 // the operation, just stop using the Xor.
6436 if (!XorCST->getValue().isNegative()) {
6437 ICI.setOperand(0, CompareVal);
6438 AddToWorkList(LHSI);
6439 return &ICI;
6440 }
6441
6442 // Was the old condition true if the operand is positive?
6443 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6444
6445 // If so, the new one isn't.
6446 isTrueIfPositive ^= true;
6447
6448 if (isTrueIfPositive)
6449 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6450 else
6451 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6452 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006453
6454 if (LHSI->hasOneUse()) {
6455 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6456 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6457 const APInt &SignBit = XorCST->getValue();
6458 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6459 ? ICI.getUnsignedPredicate()
6460 : ICI.getSignedPredicate();
6461 return new ICmpInst(Pred, LHSI->getOperand(0),
6462 ConstantInt::get(RHSV ^ SignBit));
6463 }
6464
6465 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006466 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006467 const APInt &NotSignBit = XorCST->getValue();
6468 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6469 ? ICI.getUnsignedPredicate()
6470 : ICI.getSignedPredicate();
6471 Pred = ICI.getSwappedPredicate(Pred);
6472 return new ICmpInst(Pred, LHSI->getOperand(0),
6473 ConstantInt::get(RHSV ^ NotSignBit));
6474 }
6475 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006476 }
6477 break;
6478 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6479 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6480 LHSI->getOperand(0)->hasOneUse()) {
6481 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6482
6483 // If the LHS is an AND of a truncating cast, we can widen the
6484 // and/compare to be the input width without changing the value
6485 // produced, eliminating a cast.
6486 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6487 // We can do this transformation if either the AND constant does not
6488 // have its sign bit set or if it is an equality comparison.
6489 // Extending a relational comparison when we're checking the sign
6490 // bit would not work.
6491 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006492 (ICI.isEquality() ||
6493 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006494 uint32_t BitWidth =
6495 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6496 APInt NewCST = AndCST->getValue();
6497 NewCST.zext(BitWidth);
6498 APInt NewCI = RHSV;
6499 NewCI.zext(BitWidth);
6500 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006501 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006502 ConstantInt::get(NewCST),LHSI->getName());
6503 InsertNewInstBefore(NewAnd, ICI);
6504 return new ICmpInst(ICI.getPredicate(), NewAnd,
6505 ConstantInt::get(NewCI));
6506 }
6507 }
6508
6509 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6510 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6511 // happens a LOT in code produced by the C front-end, for bitfield
6512 // access.
6513 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6514 if (Shift && !Shift->isShift())
6515 Shift = 0;
6516
6517 ConstantInt *ShAmt;
6518 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6519 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6520 const Type *AndTy = AndCST->getType(); // Type of the and.
6521
6522 // We can fold this as long as we can't shift unknown bits
6523 // into the mask. This can only happen with signed shift
6524 // rights, as they sign-extend.
6525 if (ShAmt) {
6526 bool CanFold = Shift->isLogicalShift();
6527 if (!CanFold) {
6528 // To test for the bad case of the signed shr, see if any
6529 // of the bits shifted in could be tested after the mask.
6530 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6531 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6532
6533 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6534 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6535 AndCST->getValue()) == 0)
6536 CanFold = true;
6537 }
6538
6539 if (CanFold) {
6540 Constant *NewCst;
6541 if (Shift->getOpcode() == Instruction::Shl)
6542 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6543 else
6544 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6545
6546 // Check to see if we are shifting out any of the bits being
6547 // compared.
6548 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6549 // If we shifted bits out, the fold is not going to work out.
6550 // As a special case, check to see if this means that the
6551 // result is always true or false now.
6552 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6553 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6554 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6555 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6556 } else {
6557 ICI.setOperand(1, NewCst);
6558 Constant *NewAndCST;
6559 if (Shift->getOpcode() == Instruction::Shl)
6560 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6561 else
6562 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6563 LHSI->setOperand(1, NewAndCST);
6564 LHSI->setOperand(0, Shift->getOperand(0));
6565 AddToWorkList(Shift); // Shift is dead.
6566 AddUsesToWorkList(ICI);
6567 return &ICI;
6568 }
6569 }
6570 }
6571
6572 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6573 // preferable because it allows the C<<Y expression to be hoisted out
6574 // of a loop if Y is invariant and X is not.
6575 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6576 ICI.isEquality() && !Shift->isArithmeticShift() &&
6577 isa<Instruction>(Shift->getOperand(0))) {
6578 // Compute C << Y.
6579 Value *NS;
6580 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006581 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006582 Shift->getOperand(1), "tmp");
6583 } else {
6584 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006585 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006586 Shift->getOperand(1), "tmp");
6587 }
6588 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6589
6590 // Compute X & (C << Y).
6591 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006592 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006593 InsertNewInstBefore(NewAnd, ICI);
6594
6595 ICI.setOperand(0, NewAnd);
6596 return &ICI;
6597 }
6598 }
6599 break;
6600
Chris Lattnera0141b92007-07-15 20:42:37 +00006601 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6602 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6603 if (!ShAmt) break;
6604
6605 uint32_t TypeBits = RHSV.getBitWidth();
6606
6607 // Check that the shift amount is in range. If not, don't perform
6608 // undefined shifts. When the shift is visited it will be
6609 // simplified.
6610 if (ShAmt->uge(TypeBits))
6611 break;
6612
6613 if (ICI.isEquality()) {
6614 // If we are comparing against bits always shifted out, the
6615 // comparison cannot succeed.
6616 Constant *Comp =
6617 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6618 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6619 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6620 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6621 return ReplaceInstUsesWith(ICI, Cst);
6622 }
6623
6624 if (LHSI->hasOneUse()) {
6625 // Otherwise strength reduce the shift into an and.
6626 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6627 Constant *Mask =
6628 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006629
Chris Lattnera0141b92007-07-15 20:42:37 +00006630 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006631 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006632 Mask, LHSI->getName()+".mask");
6633 Value *And = InsertNewInstBefore(AndI, ICI);
6634 return new ICmpInst(ICI.getPredicate(), And,
6635 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006636 }
6637 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006638
6639 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6640 bool TrueIfSigned = false;
6641 if (LHSI->hasOneUse() &&
6642 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6643 // (X << 31) <s 0 --> (X&1) != 0
6644 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6645 (TypeBits-ShAmt->getZExtValue()-1));
6646 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006647 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006648 Mask, LHSI->getName()+".mask");
6649 Value *And = InsertNewInstBefore(AndI, ICI);
6650
6651 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6652 And, Constant::getNullValue(And->getType()));
6653 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006654 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006655 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006656
6657 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006658 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006659 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006660 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006661 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006662
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006663 // Check that the shift amount is in range. If not, don't perform
6664 // undefined shifts. When the shift is visited it will be
6665 // simplified.
6666 uint32_t TypeBits = RHSV.getBitWidth();
6667 if (ShAmt->uge(TypeBits))
6668 break;
6669
6670 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006671
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006672 // If we are comparing against bits always shifted out, the
6673 // comparison cannot succeed.
6674 APInt Comp = RHSV << ShAmtVal;
6675 if (LHSI->getOpcode() == Instruction::LShr)
6676 Comp = Comp.lshr(ShAmtVal);
6677 else
6678 Comp = Comp.ashr(ShAmtVal);
6679
6680 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6681 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6682 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6683 return ReplaceInstUsesWith(ICI, Cst);
6684 }
6685
6686 // Otherwise, check to see if the bits shifted out are known to be zero.
6687 // If so, we can compare against the unshifted value:
6688 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006689 if (LHSI->hasOneUse() &&
6690 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006691 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6692 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6693 ConstantExpr::getShl(RHS, ShAmt));
6694 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006695
Evan Chengf30752c2008-04-23 00:38:06 +00006696 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006697 // Otherwise strength reduce the shift into an and.
6698 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6699 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006700
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006701 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006702 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006703 Mask, LHSI->getName()+".mask");
6704 Value *And = InsertNewInstBefore(AndI, ICI);
6705 return new ICmpInst(ICI.getPredicate(), And,
6706 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006707 }
6708 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006709 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006710
6711 case Instruction::SDiv:
6712 case Instruction::UDiv:
6713 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6714 // Fold this div into the comparison, producing a range check.
6715 // Determine, based on the divide type, what the range is being
6716 // checked. If there is an overflow on the low or high side, remember
6717 // it, otherwise compute the range [low, hi) bounding the new value.
6718 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006719 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6720 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6721 DivRHS))
6722 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006723 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006724
6725 case Instruction::Add:
6726 // Fold: icmp pred (add, X, C1), C2
6727
6728 if (!ICI.isEquality()) {
6729 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6730 if (!LHSC) break;
6731 const APInt &LHSV = LHSC->getValue();
6732
6733 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6734 .subtract(LHSV);
6735
6736 if (ICI.isSignedPredicate()) {
6737 if (CR.getLower().isSignBit()) {
6738 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6739 ConstantInt::get(CR.getUpper()));
6740 } else if (CR.getUpper().isSignBit()) {
6741 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6742 ConstantInt::get(CR.getLower()));
6743 }
6744 } else {
6745 if (CR.getLower().isMinValue()) {
6746 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6747 ConstantInt::get(CR.getUpper()));
6748 } else if (CR.getUpper().isMinValue()) {
6749 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6750 ConstantInt::get(CR.getLower()));
6751 }
6752 }
6753 }
6754 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 }
6756
6757 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6758 if (ICI.isEquality()) {
6759 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6760
6761 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6762 // the second operand is a constant, simplify a bit.
6763 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6764 switch (BO->getOpcode()) {
6765 case Instruction::SRem:
6766 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6767 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6768 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6769 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6770 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006771 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006772 BO->getName());
6773 InsertNewInstBefore(NewRem, ICI);
6774 return new ICmpInst(ICI.getPredicate(), NewRem,
6775 Constant::getNullValue(BO->getType()));
6776 }
6777 }
6778 break;
6779 case Instruction::Add:
6780 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6781 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6782 if (BO->hasOneUse())
6783 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6784 Subtract(RHS, BOp1C));
6785 } else if (RHSV == 0) {
6786 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6787 // efficiently invertible, or if the add has just this one use.
6788 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6789
6790 if (Value *NegVal = dyn_castNegVal(BOp1))
6791 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6792 else if (Value *NegVal = dyn_castNegVal(BOp0))
6793 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6794 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006795 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 InsertNewInstBefore(Neg, ICI);
6797 Neg->takeName(BO);
6798 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6799 }
6800 }
6801 break;
6802 case Instruction::Xor:
6803 // For the xor case, we can xor two constants together, eliminating
6804 // the explicit xor.
6805 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6806 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6807 ConstantExpr::getXor(RHS, BOC));
6808
6809 // FALLTHROUGH
6810 case Instruction::Sub:
6811 // Replace (([sub|xor] A, B) != 0) with (A != B)
6812 if (RHSV == 0)
6813 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6814 BO->getOperand(1));
6815 break;
6816
6817 case Instruction::Or:
6818 // If bits are being or'd in that are not present in the constant we
6819 // are comparing against, then the comparison could never succeed!
6820 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6821 Constant *NotCI = ConstantExpr::getNot(RHS);
6822 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6823 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6824 isICMP_NE));
6825 }
6826 break;
6827
6828 case Instruction::And:
6829 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6830 // If bits are being compared against that are and'd out, then the
6831 // comparison can never succeed!
6832 if ((RHSV & ~BOC->getValue()) != 0)
6833 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6834 isICMP_NE));
6835
6836 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6837 if (RHS == BOC && RHSV.isPowerOf2())
6838 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6839 ICmpInst::ICMP_NE, LHSI,
6840 Constant::getNullValue(RHS->getType()));
6841
6842 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006843 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 Value *X = BO->getOperand(0);
6845 Constant *Zero = Constant::getNullValue(X->getType());
6846 ICmpInst::Predicate pred = isICMP_NE ?
6847 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6848 return new ICmpInst(pred, X, Zero);
6849 }
6850
6851 // ((X & ~7) == 0) --> X < 8
6852 if (RHSV == 0 && isHighOnes(BOC)) {
6853 Value *X = BO->getOperand(0);
6854 Constant *NegX = ConstantExpr::getNeg(BOC);
6855 ICmpInst::Predicate pred = isICMP_NE ?
6856 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6857 return new ICmpInst(pred, X, NegX);
6858 }
6859 }
6860 default: break;
6861 }
6862 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6863 // Handle icmp {eq|ne} <intrinsic>, intcst.
6864 if (II->getIntrinsicID() == Intrinsic::bswap) {
6865 AddToWorkList(II);
6866 ICI.setOperand(0, II->getOperand(1));
6867 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6868 return &ICI;
6869 }
6870 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006871 }
6872 return 0;
6873}
6874
6875/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6876/// We only handle extending casts so far.
6877///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006878Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6879 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006880 Value *LHSCIOp = LHSCI->getOperand(0);
6881 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006882 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006883 Value *RHSCIOp;
6884
Chris Lattner8c756c12007-05-05 22:41:33 +00006885 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6886 // integer type is the same size as the pointer type.
6887 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6888 getTargetData().getPointerSizeInBits() ==
6889 cast<IntegerType>(DestTy)->getBitWidth()) {
6890 Value *RHSOp = 0;
6891 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006892 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006893 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6894 RHSOp = RHSC->getOperand(0);
6895 // If the pointer types don't match, insert a bitcast.
6896 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006897 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006898 }
6899
6900 if (RHSOp)
6901 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6902 }
6903
6904 // The code below only handles extension cast instructions, so far.
6905 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006906 if (LHSCI->getOpcode() != Instruction::ZExt &&
6907 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006908 return 0;
6909
Reid Spencere4d87aa2006-12-23 06:05:41 +00006910 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6911 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006912
Reid Spencere4d87aa2006-12-23 06:05:41 +00006913 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006914 // Not an extension from the same type?
6915 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006916 if (RHSCIOp->getType() != LHSCIOp->getType())
6917 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006918
Nick Lewycky4189a532008-01-28 03:48:02 +00006919 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006920 // and the other is a zext), then we can't handle this.
6921 if (CI->getOpcode() != LHSCI->getOpcode())
6922 return 0;
6923
Nick Lewycky4189a532008-01-28 03:48:02 +00006924 // Deal with equality cases early.
6925 if (ICI.isEquality())
6926 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6927
6928 // A signed comparison of sign extended values simplifies into a
6929 // signed comparison.
6930 if (isSignedCmp && isSignedExt)
6931 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6932
6933 // The other three cases all fold into an unsigned comparison.
6934 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006935 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006936
Reid Spencere4d87aa2006-12-23 06:05:41 +00006937 // If we aren't dealing with a constant on the RHS, exit early
6938 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6939 if (!CI)
6940 return 0;
6941
6942 // Compute the constant that would happen if we truncated to SrcTy then
6943 // reextended to DestTy.
6944 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6945 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6946
6947 // If the re-extended constant didn't change...
6948 if (Res2 == CI) {
6949 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6950 // For example, we might have:
6951 // %A = sext short %X to uint
6952 // %B = icmp ugt uint %A, 1330
6953 // It is incorrect to transform this into
6954 // %B = icmp ugt short %X, 1330
6955 // because %A may have negative value.
6956 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006957 // However, we allow this when the compare is EQ/NE, because they are
6958 // signless.
6959 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006960 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006961 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006962 }
6963
6964 // The re-extended constant changed so the constant cannot be represented
6965 // in the shorter type. Consequently, we cannot emit a simple comparison.
6966
6967 // First, handle some easy cases. We know the result cannot be equal at this
6968 // point so handle the ICI.isEquality() cases
6969 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006970 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006971 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006972 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006973
6974 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6975 // should have been folded away previously and not enter in here.
6976 Value *Result;
6977 if (isSignedCmp) {
6978 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006979 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006980 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006981 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006982 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006983 } else {
6984 // We're performing an unsigned comparison.
6985 if (isSignedExt) {
6986 // We're performing an unsigned comp with a sign extended value.
6987 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006988 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006989 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6990 NegOne, ICI.getName()), ICI);
6991 } else {
6992 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006993 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006994 }
6995 }
6996
6997 // Finally, return the value computed.
6998 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006999 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007000 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007001
7002 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7003 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7004 "ICmp should be folded!");
7005 if (Constant *CI = dyn_cast<Constant>(Result))
7006 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7007 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007008}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007009
Reid Spencer832254e2007-02-02 02:16:23 +00007010Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7011 return commonShiftTransforms(I);
7012}
7013
7014Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7015 return commonShiftTransforms(I);
7016}
7017
7018Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007019 if (Instruction *R = commonShiftTransforms(I))
7020 return R;
7021
7022 Value *Op0 = I.getOperand(0);
7023
7024 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7025 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7026 if (CSI->isAllOnesValue())
7027 return ReplaceInstUsesWith(I, CSI);
7028
7029 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00007030 if (!isa<VectorType>(I.getType()) &&
7031 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007032 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007033 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman0001e562009-02-24 02:00:40 +00007034
7035 // Arithmetic shifting an all-sign-bit value is a no-op.
7036 unsigned NumSignBits = ComputeNumSignBits(Op0);
7037 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7038 return ReplaceInstUsesWith(I, Op0);
7039
Chris Lattner348f6652007-12-06 01:59:46 +00007040 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007041}
7042
7043Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7044 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007046
7047 // shl X, 0 == X and shr X, 0 == X
7048 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007049 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007050 Op0 == Constant::getNullValue(Op0->getType()))
7051 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007052
Reid Spencere4d87aa2006-12-23 06:05:41 +00007053 if (isa<UndefValue>(Op0)) {
7054 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007055 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007056 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007057 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7058 }
7059 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007060 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7061 return ReplaceInstUsesWith(I, Op0);
7062 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007064 }
7065
Chris Lattner2eefe512004-04-09 19:05:30 +00007066 // Try to fold constant and into select arguments.
7067 if (isa<Constant>(Op0))
7068 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007069 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007070 return R;
7071
Reid Spencerb83eb642006-10-20 07:07:24 +00007072 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007073 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7074 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007075 return 0;
7076}
7077
Reid Spencerb83eb642006-10-20 07:07:24 +00007078Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007079 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007080 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007081
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007082 // See if we can simplify any instructions used by the instruction whose sole
7083 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007084 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007085 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007086 return &I;
7087
Chris Lattner4d5542c2006-01-06 07:12:35 +00007088 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7089 // of a signed value.
7090 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007091 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007092 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007093 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7094 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007095 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007096 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007097 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007098 }
7099
7100 // ((X*C1) << C2) == (X * (C1 << C2))
7101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7102 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7103 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007104 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007105 ConstantExpr::getShl(BOOp, Op1));
7106
7107 // Try to fold constant and into select arguments.
7108 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7109 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7110 return R;
7111 if (isa<PHINode>(Op0))
7112 if (Instruction *NV = FoldOpIntoPhi(I))
7113 return NV;
7114
Chris Lattner8999dd32007-12-22 09:07:47 +00007115 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7116 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7117 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7118 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7119 // place. Don't try to do this transformation in this case. Also, we
7120 // require that the input operand is a shift-by-constant so that we have
7121 // confidence that the shifts will get folded together. We could do this
7122 // xform in more cases, but it is unlikely to be profitable.
7123 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7124 isa<ConstantInt>(TrOp->getOperand(1))) {
7125 // Okay, we'll do this xform. Make the shift of shift.
7126 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007127 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007128 I.getName());
7129 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7130
7131 // For logical shifts, the truncation has the effect of making the high
7132 // part of the register be zeros. Emulate this by inserting an AND to
7133 // clear the top bits as needed. This 'and' will usually be zapped by
7134 // other xforms later if dead.
7135 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7136 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7137 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7138
7139 // The mask we constructed says what the trunc would do if occurring
7140 // between the shifts. We want to know the effect *after* the second
7141 // shift. We know that it is a logical shift by a constant, so adjust the
7142 // mask as appropriate.
7143 if (I.getOpcode() == Instruction::Shl)
7144 MaskV <<= Op1->getZExtValue();
7145 else {
7146 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7147 MaskV = MaskV.lshr(Op1->getZExtValue());
7148 }
7149
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007150 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007151 TI->getName());
7152 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7153
7154 // Return the value truncated to the interesting size.
7155 return new TruncInst(And, I.getType());
7156 }
7157 }
7158
Chris Lattner4d5542c2006-01-06 07:12:35 +00007159 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007160 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7161 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7162 Value *V1, *V2;
7163 ConstantInt *CC;
7164 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007165 default: break;
7166 case Instruction::Add:
7167 case Instruction::And:
7168 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007169 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007170 // These operators commute.
7171 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007172 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007173 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007174 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007175 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007176 Op0BO->getName());
7177 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007178 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007179 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007180 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007181 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007182 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007183 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007184 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007185 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007186
Chris Lattner150f12a2005-09-18 06:30:59 +00007187 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007188 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007189 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007190 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007191 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7192 m_ConstantInt(CC))) &&
7193 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007194 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007195 Op0BO->getOperand(0), Op1,
7196 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007197 InsertNewInstBefore(YS, I); // (Y << C)
7198 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007199 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007200 V1->getName()+".mask");
7201 InsertNewInstBefore(XM, I); // X & (CC << C)
7202
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007203 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007204 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007205 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007206
Reid Spencera07cb7d2007-02-02 14:41:37 +00007207 // FALL THROUGH.
7208 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007209 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007210 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007211 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007212 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007213 Op0BO->getOperand(1), Op1,
7214 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007215 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007216 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007217 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007218 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007219 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007220 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007221 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007222 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007223 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007224
Chris Lattner13d4ab42006-05-31 21:14:00 +00007225 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007226 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7227 match(Op0BO->getOperand(0),
7228 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007229 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007230 cast<BinaryOperator>(Op0BO->getOperand(0))
7231 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007232 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007233 Op0BO->getOperand(1), Op1,
7234 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007235 InsertNewInstBefore(YS, I); // (Y << C)
7236 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007237 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007238 V1->getName()+".mask");
7239 InsertNewInstBefore(XM, I); // X & (CC << C)
7240
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007241 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007242 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007243
Chris Lattner11021cb2005-09-18 05:12:10 +00007244 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007245 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007246 }
7247
7248
7249 // If the operand is an bitwise operator with a constant RHS, and the
7250 // shift is the only use, we can pull it out of the shift.
7251 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7252 bool isValid = true; // Valid only for And, Or, Xor
7253 bool highBitSet = false; // Transform if high bit of constant set?
7254
7255 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007256 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007257 case Instruction::Add:
7258 isValid = isLeftShift;
7259 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007260 case Instruction::Or:
7261 case Instruction::Xor:
7262 highBitSet = false;
7263 break;
7264 case Instruction::And:
7265 highBitSet = true;
7266 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007267 }
7268
7269 // If this is a signed shift right, and the high bit is modified
7270 // by the logical operation, do not perform the transformation.
7271 // The highBitSet boolean indicates the value of the high bit of
7272 // the constant which would cause it to be modified for this
7273 // operation.
7274 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007275 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007276 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007277
7278 if (isValid) {
7279 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7280
7281 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007282 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007283 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007284 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007285
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007286 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007287 NewRHS);
7288 }
7289 }
7290 }
7291 }
7292
Chris Lattnerad0124c2006-01-06 07:52:12 +00007293 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007294 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7295 if (ShiftOp && !ShiftOp->isShift())
7296 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007297
Reid Spencerb83eb642006-10-20 07:07:24 +00007298 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007299 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007300 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7301 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007302 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7303 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7304 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007305
Zhou Sheng4351c642007-04-02 08:20:41 +00007306 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007307 if (AmtSum > TypeBits)
7308 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007309
7310 const IntegerType *Ty = cast<IntegerType>(I.getType());
7311
7312 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007313 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007314 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007315 ConstantInt::get(Ty, AmtSum));
7316 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7317 I.getOpcode() == Instruction::AShr) {
7318 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007319 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007320 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7321 I.getOpcode() == Instruction::LShr) {
7322 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7323 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007324 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007325 InsertNewInstBefore(Shift, I);
7326
Zhou Shenge9e03f62007-03-28 15:02:20 +00007327 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007328 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007329 }
7330
Chris Lattnerb87056f2007-02-05 00:57:54 +00007331 // Okay, if we get here, one shift must be left, and the other shift must be
7332 // right. See if the amounts are equal.
7333 if (ShiftAmt1 == ShiftAmt2) {
7334 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7335 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007336 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007337 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007338 }
7339 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7340 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007341 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007342 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007343 }
7344 // We can simplify ((X << C) >>s C) into a trunc + sext.
7345 // NOTE: we could do this for any C, but that would make 'unusual' integer
7346 // types. For now, just stick to ones well-supported by the code
7347 // generators.
7348 const Type *SExtType = 0;
7349 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007350 case 1 :
7351 case 8 :
7352 case 16 :
7353 case 32 :
7354 case 64 :
7355 case 128:
7356 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7357 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007358 default: break;
7359 }
7360 if (SExtType) {
7361 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7362 InsertNewInstBefore(NewTrunc, I);
7363 return new SExtInst(NewTrunc, Ty);
7364 }
7365 // Otherwise, we can't handle it yet.
7366 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007367 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007368
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007369 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007370 if (I.getOpcode() == Instruction::Shl) {
7371 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7372 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007373 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007374 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007375 InsertNewInstBefore(Shift, I);
7376
Reid Spencer55702aa2007-03-25 21:11:44 +00007377 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007378 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007379 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007380
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007381 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007382 if (I.getOpcode() == Instruction::LShr) {
7383 assert(ShiftOp->getOpcode() == Instruction::Shl);
7384 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007385 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007386 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007387
Reid Spencerd5e30f02007-03-26 17:18:58 +00007388 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007390 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007391
7392 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7393 } else {
7394 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007395 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007396
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007397 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007398 if (I.getOpcode() == Instruction::Shl) {
7399 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7400 ShiftOp->getOpcode() == Instruction::AShr);
7401 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007402 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007403 ConstantInt::get(Ty, ShiftDiff));
7404 InsertNewInstBefore(Shift, I);
7405
Reid Spencer55702aa2007-03-25 21:11:44 +00007406 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007407 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007408 }
7409
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007410 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007411 if (I.getOpcode() == Instruction::LShr) {
7412 assert(ShiftOp->getOpcode() == Instruction::Shl);
7413 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007414 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007415 InsertNewInstBefore(Shift, I);
7416
Reid Spencer68d27cf2007-03-26 23:45:51 +00007417 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007418 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007419 }
7420
7421 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007422 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007423 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007424 return 0;
7425}
7426
Chris Lattnera1be5662002-05-02 17:06:02 +00007427
Chris Lattnercfd65102005-10-29 04:36:15 +00007428/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7429/// expression. If so, decompose it, returning some value X, such that Val is
7430/// X*Scale+Offset.
7431///
7432static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007433 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007434 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007435 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007436 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007437 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007438 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007439 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7440 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7441 if (I->getOpcode() == Instruction::Shl) {
7442 // This is a value scaled by '1 << the shift amt'.
7443 Scale = 1U << RHS->getZExtValue();
7444 Offset = 0;
7445 return I->getOperand(0);
7446 } else if (I->getOpcode() == Instruction::Mul) {
7447 // This value is scaled by 'RHS'.
7448 Scale = RHS->getZExtValue();
7449 Offset = 0;
7450 return I->getOperand(0);
7451 } else if (I->getOpcode() == Instruction::Add) {
7452 // We have X+C. Check to see if we really have (X*C2)+C1,
7453 // where C1 is divisible by C2.
7454 unsigned SubScale;
7455 Value *SubVal =
7456 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7457 Offset += RHS->getZExtValue();
7458 Scale = SubScale;
7459 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007460 }
7461 }
7462 }
7463
7464 // Otherwise, we can't look past this.
7465 Scale = 1;
7466 Offset = 0;
7467 return Val;
7468}
7469
7470
Chris Lattnerb3f83972005-10-24 06:03:58 +00007471/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7472/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007473Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007474 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007475 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007476
Chris Lattnerb53c2382005-10-24 06:22:12 +00007477 // Remove any uses of AI that are dead.
7478 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007479
Chris Lattnerb53c2382005-10-24 06:22:12 +00007480 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7481 Instruction *User = cast<Instruction>(*UI++);
7482 if (isInstructionTriviallyDead(User)) {
7483 while (UI != E && *UI == User)
7484 ++UI; // If this instruction uses AI more than once, don't break UI.
7485
Chris Lattnerb53c2382005-10-24 06:22:12 +00007486 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007487 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007488 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007489 }
7490 }
7491
Chris Lattnerb3f83972005-10-24 06:03:58 +00007492 // Get the type really allocated and the type casted to.
7493 const Type *AllocElTy = AI.getAllocatedType();
7494 const Type *CastElTy = PTy->getElementType();
7495 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007496
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007497 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7498 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007499 if (CastElTyAlign < AllocElTyAlign) return 0;
7500
Chris Lattner39387a52005-10-24 06:35:18 +00007501 // If the allocation has multiple uses, only promote it if we are strictly
7502 // increasing the alignment of the resultant allocation. If we keep it the
7503 // same, we open the door to infinite loops of various kinds.
7504 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7505
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007506 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7507 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007508 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007509
Chris Lattner455fcc82005-10-29 03:19:53 +00007510 // See if we can satisfy the modulus by pulling a scale out of the array
7511 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007512 unsigned ArraySizeScale;
7513 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007514 Value *NumElements = // See if the array size is a decomposable linear expr.
7515 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7516
Chris Lattner455fcc82005-10-29 03:19:53 +00007517 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7518 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007519 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7520 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007521
Chris Lattner455fcc82005-10-29 03:19:53 +00007522 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7523 Value *Amt = 0;
7524 if (Scale == 1) {
7525 Amt = NumElements;
7526 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007527 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007528 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7529 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007530 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007531 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007532 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007534 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007535 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007536 }
7537
Jeff Cohen86796be2007-04-04 16:58:57 +00007538 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7539 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007540 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007541 Amt = InsertNewInstBefore(Tmp, AI);
7542 }
7543
Chris Lattnerb3f83972005-10-24 06:03:58 +00007544 AllocationInst *New;
7545 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007546 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007547 else
Chris Lattner6934a042007-02-11 01:23:03 +00007548 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007549 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007550 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007551
7552 // If the allocation has multiple uses, insert a cast and change all things
7553 // that used it to use the new cast. This will also hack on CI, but it will
7554 // die soon.
7555 if (!AI.hasOneUse()) {
7556 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007557 // New is the allocation instruction, pointer typed. AI is the original
7558 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7559 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007560 InsertNewInstBefore(NewCast, AI);
7561 AI.replaceAllUsesWith(NewCast);
7562 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007563 return ReplaceInstUsesWith(CI, New);
7564}
7565
Chris Lattner70074e02006-05-13 02:06:03 +00007566/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007567/// and return it as type Ty without inserting any new casts and without
7568/// changing the computed value. This is used by code that tries to decide
7569/// whether promoting or shrinking integer operations to wider or smaller types
7570/// will allow us to eliminate a truncate or extend.
7571///
7572/// This is a truncation operation if Ty is smaller than V->getType(), or an
7573/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007574///
7575/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7576/// should return true if trunc(V) can be computed by computing V in the smaller
7577/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7578/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7579/// efficiently truncated.
7580///
7581/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7582/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7583/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007584bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7585 unsigned CastOpc,
7586 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007587 // We can always evaluate constants in another type.
7588 if (isa<ConstantInt>(V))
7589 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007590
7591 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007592 if (!I) return false;
7593
7594 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007595
Chris Lattner951626b2007-08-02 06:11:14 +00007596 // If this is an extension or truncate, we can often eliminate it.
7597 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7598 // If this is a cast from the destination type, we can trivially eliminate
7599 // it, and this will remove a cast overall.
7600 if (I->getOperand(0)->getType() == Ty) {
7601 // If the first operand is itself a cast, and is eliminable, do not count
7602 // this as an eliminable cast. We would prefer to eliminate those two
7603 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007604 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007605 ++NumCastsRemoved;
7606 return true;
7607 }
7608 }
7609
7610 // We can't extend or shrink something that has multiple uses: doing so would
7611 // require duplicating the instruction in general, which isn't profitable.
7612 if (!I->hasOneUse()) return false;
7613
Evan Chengf35fd542009-01-15 17:01:23 +00007614 unsigned Opc = I->getOpcode();
7615 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007616 case Instruction::Add:
7617 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007618 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007619 case Instruction::And:
7620 case Instruction::Or:
7621 case Instruction::Xor:
7622 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007623 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007624 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007625 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007626 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007627
Chris Lattner46b96052006-11-29 07:18:39 +00007628 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007629 // If we are truncating the result of this SHL, and if it's a shift of a
7630 // constant amount, we can always perform a SHL in a smaller type.
7631 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007632 uint32_t BitWidth = Ty->getBitWidth();
7633 if (BitWidth < OrigTy->getBitWidth() &&
7634 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007635 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007636 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007637 }
7638 break;
7639 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007640 // If this is a truncate of a logical shr, we can truncate it to a smaller
7641 // lshr iff we know that the bits we would otherwise be shifting in are
7642 // already zeros.
7643 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007644 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7645 uint32_t BitWidth = Ty->getBitWidth();
7646 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007647 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007648 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7649 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007650 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007651 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007652 }
7653 }
Chris Lattner46b96052006-11-29 07:18:39 +00007654 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007655 case Instruction::ZExt:
7656 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007657 case Instruction::Trunc:
7658 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007659 // can safely replace it. Note that replacing it does not reduce the number
7660 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007661 if (Opc == CastOpc)
7662 return true;
7663
7664 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007665 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007666 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007667 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007668 case Instruction::Select: {
7669 SelectInst *SI = cast<SelectInst>(I);
7670 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007671 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007672 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007673 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007674 }
Chris Lattner8114b712008-06-18 04:00:49 +00007675 case Instruction::PHI: {
7676 // We can change a phi if we can change all operands.
7677 PHINode *PN = cast<PHINode>(I);
7678 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7679 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007680 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007681 return false;
7682 return true;
7683 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007684 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007685 // TODO: Can handle more cases here.
7686 break;
7687 }
7688
7689 return false;
7690}
7691
7692/// EvaluateInDifferentType - Given an expression that
7693/// CanEvaluateInDifferentType returns true for, actually insert the code to
7694/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007695Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007696 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007697 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007698 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007699
7700 // Otherwise, it must be an instruction.
7701 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007702 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007703 unsigned Opc = I->getOpcode();
7704 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007705 case Instruction::Add:
7706 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007707 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007708 case Instruction::And:
7709 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007710 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007711 case Instruction::AShr:
7712 case Instruction::LShr:
7713 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007714 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007715 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007716 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007717 break;
7718 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007719 case Instruction::Trunc:
7720 case Instruction::ZExt:
7721 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007722 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007723 // just return the source. There's no need to insert it because it is not
7724 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007725 if (I->getOperand(0)->getType() == Ty)
7726 return I->getOperand(0);
7727
Chris Lattner8114b712008-06-18 04:00:49 +00007728 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007729 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007730 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007731 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007732 case Instruction::Select: {
7733 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7734 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7735 Res = SelectInst::Create(I->getOperand(0), True, False);
7736 break;
7737 }
Chris Lattner8114b712008-06-18 04:00:49 +00007738 case Instruction::PHI: {
7739 PHINode *OPN = cast<PHINode>(I);
7740 PHINode *NPN = PHINode::Create(Ty);
7741 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7742 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7743 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7744 }
7745 Res = NPN;
7746 break;
7747 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007748 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007749 // TODO: Can handle more cases here.
7750 assert(0 && "Unreachable!");
7751 break;
7752 }
7753
Chris Lattner8114b712008-06-18 04:00:49 +00007754 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007755 return InsertNewInstBefore(Res, *I);
7756}
7757
Reid Spencer3da59db2006-11-27 01:05:10 +00007758/// @brief Implement the transforms common to all CastInst visitors.
7759Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007760 Value *Src = CI.getOperand(0);
7761
Dan Gohman23d9d272007-05-11 21:10:54 +00007762 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007763 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007764 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007765 if (Instruction::CastOps opc =
7766 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7767 // The first cast (CSrc) is eliminable so we need to fix up or replace
7768 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007769 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007770 }
7771 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007772
Reid Spencer3da59db2006-11-27 01:05:10 +00007773 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007774 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7775 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7776 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007777
7778 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007779 if (isa<PHINode>(Src))
7780 if (Instruction *NV = FoldOpIntoPhi(CI))
7781 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007782
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 return 0;
7784}
7785
Chris Lattner46cd5a12009-01-09 05:44:56 +00007786/// FindElementAtOffset - Given a type and a constant offset, determine whether
7787/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007788/// the specified offset. If so, fill them into NewIndices and return the
7789/// resultant element type, otherwise return null.
7790static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7791 SmallVectorImpl<Value*> &NewIndices,
7792 const TargetData *TD) {
7793 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007794
7795 // Start with the index over the outer type. Note that the type size
7796 // might be zero (even if the offset isn't zero) if the indexed type
7797 // is something like [0 x {int, int}]
7798 const Type *IntPtrTy = TD->getIntPtrType();
7799 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007800 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007801 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007802 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007803
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007804 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007805 if (Offset < 0) {
7806 --FirstIdx;
7807 Offset += TySize;
7808 assert(Offset >= 0);
7809 }
7810 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7811 }
7812
7813 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7814
7815 // Index into the types. If we fail, set OrigBase to null.
7816 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007817 // Indexing into tail padding between struct/array elements.
7818 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007819 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007820
Chris Lattner46cd5a12009-01-09 05:44:56 +00007821 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7822 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007823 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7824 "Offset must stay within the indexed type");
7825
Chris Lattner46cd5a12009-01-09 05:44:56 +00007826 unsigned Elt = SL->getElementContainingOffset(Offset);
7827 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7828
7829 Offset -= SL->getElementOffset(Elt);
7830 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007831 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007832 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007833 assert(EltSize && "Cannot index into a zero-sized array");
7834 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7835 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007836 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007837 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007838 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007839 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007840 }
7841 }
7842
Chris Lattner3914f722009-01-24 01:00:13 +00007843 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007844}
7845
Chris Lattnerd3e28342007-04-27 17:44:50 +00007846/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7847Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7848 Value *Src = CI.getOperand(0);
7849
Chris Lattnerd3e28342007-04-27 17:44:50 +00007850 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007851 // If casting the result of a getelementptr instruction with no offset, turn
7852 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007853 if (GEP->hasAllZeroIndices()) {
7854 // Changing the cast operand is usually not a good idea but it is safe
7855 // here because the pointer operand is being replaced with another
7856 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007857 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007858 CI.setOperand(0, GEP->getOperand(0));
7859 return &CI;
7860 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007861
7862 // If the GEP has a single use, and the base pointer is a bitcast, and the
7863 // GEP computes a constant offset, see if we can convert these three
7864 // instructions into fewer. This typically happens with unions and other
7865 // non-type-safe code.
7866 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7867 if (GEP->hasAllConstantIndices()) {
7868 // We are guaranteed to get a constant from EmitGEPOffset.
7869 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7870 int64_t Offset = OffsetV->getSExtValue();
7871
7872 // Get the base pointer input of the bitcast, and the type it points to.
7873 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7874 const Type *GEPIdxTy =
7875 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007876 SmallVector<Value*, 8> NewIndices;
7877 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7878 // If we were able to index down into an element, create the GEP
7879 // and bitcast the result. This eliminates one bitcast, potentially
7880 // two.
7881 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7882 NewIndices.begin(),
7883 NewIndices.end(), "");
7884 InsertNewInstBefore(NGEP, CI);
7885 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007886
Chris Lattner46cd5a12009-01-09 05:44:56 +00007887 if (isa<BitCastInst>(CI))
7888 return new BitCastInst(NGEP, CI.getType());
7889 assert(isa<PtrToIntInst>(CI));
7890 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007891 }
7892 }
7893 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007894 }
7895
7896 return commonCastTransforms(CI);
7897}
7898
7899
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7901/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007902/// cases.
7903/// @brief Implement the transforms common to CastInst with integer operands
7904Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7905 if (Instruction *Result = commonCastTransforms(CI))
7906 return Result;
7907
7908 Value *Src = CI.getOperand(0);
7909 const Type *SrcTy = Src->getType();
7910 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007911 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7912 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007913
Reid Spencer3da59db2006-11-27 01:05:10 +00007914 // See if we can simplify any instructions used by the LHS whose sole
7915 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007916 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007917 return &CI;
7918
7919 // If the source isn't an instruction or has more than one use then we
7920 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007921 Instruction *SrcI = dyn_cast<Instruction>(Src);
7922 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007923 return 0;
7924
Chris Lattnerc739cd62007-03-03 05:27:34 +00007925 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007926 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007927 if (!isa<BitCastInst>(CI) &&
7928 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007929 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007930 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007931 // eliminates the cast, so it is always a win. If this is a zero-extension,
7932 // we need to do an AND to maintain the clear top-part of the computation,
7933 // so we require that the input have eliminated at least one cast. If this
7934 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007935 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007936 bool DoXForm = false;
7937 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938 switch (CI.getOpcode()) {
7939 default:
7940 // All the others use floating point so we shouldn't actually
7941 // get here because of the check above.
7942 assert(0 && "Unknown cast type");
7943 case Instruction::Trunc:
7944 DoXForm = true;
7945 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007946 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007948 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007949 // If it's unnecessary to issue an AND to clear the high bits, it's
7950 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007951 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007952 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7953 if (MaskedValueIsZero(TryRes, Mask))
7954 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007955
7956 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007957 if (TryI->use_empty())
7958 EraseInstFromFunction(*TryI);
7959 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007961 }
Evan Chengf35fd542009-01-15 17:01:23 +00007962 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007964 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007965 // If we do not have to emit the truncate + sext pair, then it's always
7966 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007967 //
7968 // It's not safe to eliminate the trunc + sext pair if one of the
7969 // eliminated cast is a truncate. e.g.
7970 // t2 = trunc i32 t1 to i16
7971 // t3 = sext i16 t2 to i32
7972 // !=
7973 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00007974 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007975 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7976 if (NumSignBits > (DestBitSize - SrcBitSize))
7977 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007978
7979 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007980 if (TryI->use_empty())
7981 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007982 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007983 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007984 }
Evan Chengf35fd542009-01-15 17:01:23 +00007985 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007986
7987 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00007988 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7989 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00007990 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7991 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007992 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00007993 // Just replace this cast with the result.
7994 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007995
Reid Spencer3da59db2006-11-27 01:05:10 +00007996 assert(Res->getType() == DestTy);
7997 switch (CI.getOpcode()) {
7998 default: assert(0 && "Unknown cast type!");
7999 case Instruction::Trunc:
8000 case Instruction::BitCast:
8001 // Just replace this cast with the result.
8002 return ReplaceInstUsesWith(CI, Res);
8003 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008004 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008005
8006 // If the high bits are already zero, just replace this cast with the
8007 // result.
8008 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8009 if (MaskedValueIsZero(Res, Mask))
8010 return ReplaceInstUsesWith(CI, Res);
8011
8012 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008013 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8014 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008015 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008017 case Instruction::SExt: {
8018 // If the high bits are already filled with sign bit, just replace this
8019 // cast with the result.
8020 unsigned NumSignBits = ComputeNumSignBits(Res);
8021 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008022 return ReplaceInstUsesWith(CI, Res);
8023
Reid Spencer3da59db2006-11-27 01:05:10 +00008024 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008025 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008026 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8027 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008028 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008029 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008030 }
8031 }
8032
8033 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8034 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8035
8036 switch (SrcI->getOpcode()) {
8037 case Instruction::Add:
8038 case Instruction::Mul:
8039 case Instruction::And:
8040 case Instruction::Or:
8041 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008042 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008043 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8044 // Don't insert two casts if they cannot be eliminated. We allow
8045 // two casts to be inserted if the sizes are the same. This could
8046 // only be converting signedness, which is a noop.
8047 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008048 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8049 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008050 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008051 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8052 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008053 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008054 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 }
8056 }
8057
8058 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8059 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8060 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008061 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008062 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008063 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008064 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008065 }
8066 break;
8067 case Instruction::SDiv:
8068 case Instruction::UDiv:
8069 case Instruction::SRem:
8070 case Instruction::URem:
8071 // If we are just changing the sign, rewrite.
8072 if (DestBitSize == SrcBitSize) {
8073 // Don't insert two casts if they cannot be eliminated. We allow
8074 // two casts to be inserted if the sizes are the same. This could
8075 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008076 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8077 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008078 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8079 Op0, DestTy, *SrcI);
8080 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8081 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008083 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8084 }
8085 }
8086 break;
8087
8088 case Instruction::Shl:
8089 // Allow changing the sign of the source operand. Do not allow
8090 // changing the size of the shift, UNLESS the shift amount is a
8091 // constant. We must not change variable sized shifts to a smaller
8092 // size, because it is undefined to shift more bits out than exist
8093 // in the value.
8094 if (DestBitSize == SrcBitSize ||
8095 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008096 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8097 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008098 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8099 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008100 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008101 }
8102 break;
8103 case Instruction::AShr:
8104 // If this is a signed shr, and if all bits shifted in are about to be
8105 // truncated off, turn it into an unsigned shr to allow greater
8106 // simplifications.
8107 if (DestBitSize < SrcBitSize &&
8108 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008109 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8111 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008112 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 }
8114 }
8115 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008116 }
8117 return 0;
8118}
8119
Chris Lattner8a9f5712007-04-11 06:57:46 +00008120Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008121 if (Instruction *Result = commonIntCastTransforms(CI))
8122 return Result;
8123
8124 Value *Src = CI.getOperand(0);
8125 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008126 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8127 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008128
8129 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8130 switch (SrcI->getOpcode()) {
8131 default: break;
8132 case Instruction::LShr:
8133 // We can shrink lshr to something smaller if we know the bits shifted in
8134 // are already zeros.
8135 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008136 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008137
8138 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008139 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008140 Value* SrcIOp0 = SrcI->getOperand(0);
8141 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008142 if (ShAmt >= DestBitWidth) // All zeros.
8143 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8144
8145 // Okay, we can shrink this. Truncate the input, then return a new
8146 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008147 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8148 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8149 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008150 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008151 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008152 } else { // This is a variable shr.
8153
8154 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8155 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8156 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008157 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008158 Value *One = ConstantInt::get(SrcI->getType(), 1);
8159
Reid Spencer832254e2007-02-02 02:16:23 +00008160 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008161 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008162 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008163 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008164 SrcI->getOperand(0),
8165 "tmp"), CI);
8166 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008167 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008168 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008169 }
8170 break;
8171 }
8172 }
8173
8174 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008175}
8176
Evan Chengb98a10e2008-03-24 00:21:34 +00008177/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8178/// in order to eliminate the icmp.
8179Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8180 bool DoXform) {
8181 // If we are just checking for a icmp eq of a single bit and zext'ing it
8182 // to an integer, then shift the bit to the appropriate place and then
8183 // cast to integer to avoid the comparison.
8184 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8185 const APInt &Op1CV = Op1C->getValue();
8186
8187 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8188 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8189 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8190 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8191 if (!DoXform) return ICI;
8192
8193 Value *In = ICI->getOperand(0);
8194 Value *Sh = ConstantInt::get(In->getType(),
8195 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008196 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008197 In->getName()+".lobit"),
8198 CI);
8199 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008200 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008201 false/*ZExt*/, "tmp", &CI);
8202
8203 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8204 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008205 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008206 In->getName()+".not"),
8207 CI);
8208 }
8209
8210 return ReplaceInstUsesWith(CI, In);
8211 }
8212
8213
8214
8215 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8216 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8217 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8218 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8219 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8220 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8221 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8222 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8223 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8224 // This only works for EQ and NE
8225 ICI->isEquality()) {
8226 // If Op1C some other power of two, convert:
8227 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8228 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8229 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8230 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8231
8232 APInt KnownZeroMask(~KnownZero);
8233 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8234 if (!DoXform) return ICI;
8235
8236 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8237 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8238 // (X&4) == 2 --> false
8239 // (X&4) != 2 --> true
8240 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8241 Res = ConstantExpr::getZExt(Res, CI.getType());
8242 return ReplaceInstUsesWith(CI, Res);
8243 }
8244
8245 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8246 Value *In = ICI->getOperand(0);
8247 if (ShiftAmt) {
8248 // Perform a logical shr by shiftamt.
8249 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008250 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008251 ConstantInt::get(In->getType(), ShiftAmt),
8252 In->getName()+".lobit"), CI);
8253 }
8254
8255 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8256 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008257 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008258 InsertNewInstBefore(cast<Instruction>(In), CI);
8259 }
8260
8261 if (CI.getType() == In->getType())
8262 return ReplaceInstUsesWith(CI, In);
8263 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008264 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008265 }
8266 }
8267 }
8268
8269 return 0;
8270}
8271
Chris Lattner8a9f5712007-04-11 06:57:46 +00008272Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 // If one of the common conversion will work ..
8274 if (Instruction *Result = commonIntCastTransforms(CI))
8275 return Result;
8276
8277 Value *Src = CI.getOperand(0);
8278
Chris Lattnera84f47c2009-02-17 20:47:23 +00008279 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8280 // types and if the sizes are just right we can convert this into a logical
8281 // 'and' which will be much cheaper than the pair of casts.
8282 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8283 // Get the sizes of the types involved. We know that the intermediate type
8284 // will be smaller than A or C, but don't know the relation between A and C.
8285 Value *A = CSrc->getOperand(0);
8286 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8287 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8288 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8289 // If we're actually extending zero bits, then if
8290 // SrcSize < DstSize: zext(a & mask)
8291 // SrcSize == DstSize: a & mask
8292 // SrcSize > DstSize: trunc(a) & mask
8293 if (SrcSize < DstSize) {
8294 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8295 Constant *AndConst = ConstantInt::get(AndValue);
8296 Instruction *And =
8297 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8298 InsertNewInstBefore(And, CI);
8299 return new ZExtInst(And, CI.getType());
8300 } else if (SrcSize == DstSize) {
8301 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8302 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8303 } else if (SrcSize > DstSize) {
8304 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8305 InsertNewInstBefore(Trunc, CI);
8306 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8307 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 }
8309 }
8310
Evan Chengb98a10e2008-03-24 00:21:34 +00008311 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8312 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008313
Evan Chengb98a10e2008-03-24 00:21:34 +00008314 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8315 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8316 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8317 // of the (zext icmp) will be transformed.
8318 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8319 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8320 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8321 (transformZExtICmp(LHS, CI, false) ||
8322 transformZExtICmp(RHS, CI, false))) {
8323 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8324 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008325 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008326 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008327 }
8328
Reid Spencer3da59db2006-11-27 01:05:10 +00008329 return 0;
8330}
8331
Chris Lattner8a9f5712007-04-11 06:57:46 +00008332Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008333 if (Instruction *I = commonIntCastTransforms(CI))
8334 return I;
8335
Chris Lattner8a9f5712007-04-11 06:57:46 +00008336 Value *Src = CI.getOperand(0);
8337
Dan Gohman1975d032008-10-30 20:40:10 +00008338 // Canonicalize sign-extend from i1 to a select.
8339 if (Src->getType() == Type::Int1Ty)
8340 return SelectInst::Create(Src,
8341 ConstantInt::getAllOnesValue(CI.getType()),
8342 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008343
8344 // See if the value being truncated is already sign extended. If so, just
8345 // eliminate the trunc/sext pair.
8346 if (getOpcode(Src) == Instruction::Trunc) {
8347 Value *Op = cast<User>(Src)->getOperand(0);
8348 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8349 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8350 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8351 unsigned NumSignBits = ComputeNumSignBits(Op);
8352
8353 if (OpBits == DestBits) {
8354 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8355 // bits, it is already ready.
8356 if (NumSignBits > DestBits-MidBits)
8357 return ReplaceInstUsesWith(CI, Op);
8358 } else if (OpBits < DestBits) {
8359 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8360 // bits, just sext from i32.
8361 if (NumSignBits > OpBits-MidBits)
8362 return new SExtInst(Op, CI.getType(), "tmp");
8363 } else {
8364 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8365 // bits, just truncate to i32.
8366 if (NumSignBits > OpBits-MidBits)
8367 return new TruncInst(Op, CI.getType(), "tmp");
8368 }
8369 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008370
8371 // If the input is a shl/ashr pair of a same constant, then this is a sign
8372 // extension from a smaller value. If we could trust arbitrary bitwidth
8373 // integers, we could turn this into a truncate to the smaller bit and then
8374 // use a sext for the whole extension. Since we don't, look deeper and check
8375 // for a truncate. If the source and dest are the same type, eliminate the
8376 // trunc and extend and just do shifts. For example, turn:
8377 // %a = trunc i32 %i to i8
8378 // %b = shl i8 %a, 6
8379 // %c = ashr i8 %b, 6
8380 // %d = sext i8 %c to i32
8381 // into:
8382 // %a = shl i32 %i, 30
8383 // %d = ashr i32 %a, 30
8384 Value *A = 0;
8385 ConstantInt *BA = 0, *CA = 0;
8386 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8387 m_ConstantInt(CA))) &&
8388 BA == CA && isa<TruncInst>(A)) {
8389 Value *I = cast<TruncInst>(A)->getOperand(0);
8390 if (I->getType() == CI.getType()) {
8391 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8392 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8393 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8394 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8395 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8396 CI.getName()), CI);
8397 return BinaryOperator::CreateAShr(I, ShAmtV);
8398 }
8399 }
8400
Chris Lattnerba417832007-04-11 06:12:58 +00008401 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008402}
8403
Chris Lattnerb7530652008-01-27 05:29:54 +00008404/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8405/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008406static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008407 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008408 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008409 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8410 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008411 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008412 return 0;
8413}
8414
8415/// LookThroughFPExtensions - If this is an fp extension instruction, look
8416/// through it until we get the source value.
8417static Value *LookThroughFPExtensions(Value *V) {
8418 if (Instruction *I = dyn_cast<Instruction>(V))
8419 if (I->getOpcode() == Instruction::FPExt)
8420 return LookThroughFPExtensions(I->getOperand(0));
8421
8422 // If this value is a constant, return the constant in the smallest FP type
8423 // that can accurately represent it. This allows us to turn
8424 // (float)((double)X+2.0) into x+2.0f.
8425 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8426 if (CFP->getType() == Type::PPC_FP128Ty)
8427 return V; // No constant folding of this.
8428 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008429 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008430 return V;
8431 if (CFP->getType() == Type::DoubleTy)
8432 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008433 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008434 return V;
8435 // Don't try to shrink to various long double types.
8436 }
8437
8438 return V;
8439}
8440
8441Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8442 if (Instruction *I = commonCastTransforms(CI))
8443 return I;
8444
8445 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8446 // smaller than the destination type, we can eliminate the truncate by doing
8447 // the add as the smaller type. This applies to add/sub/mul/div as well as
8448 // many builtins (sqrt, etc).
8449 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8450 if (OpI && OpI->hasOneUse()) {
8451 switch (OpI->getOpcode()) {
8452 default: break;
8453 case Instruction::Add:
8454 case Instruction::Sub:
8455 case Instruction::Mul:
8456 case Instruction::FDiv:
8457 case Instruction::FRem:
8458 const Type *SrcTy = OpI->getType();
8459 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8460 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8461 if (LHSTrunc->getType() != SrcTy &&
8462 RHSTrunc->getType() != SrcTy) {
8463 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8464 // If the source types were both smaller than the destination type of
8465 // the cast, do this xform.
8466 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8467 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8468 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8469 CI.getType(), CI);
8470 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8471 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008472 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008473 }
8474 }
8475 break;
8476 }
8477 }
8478 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008479}
8480
8481Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8482 return commonCastTransforms(CI);
8483}
8484
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008485Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008486 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8487 if (OpI == 0)
8488 return commonCastTransforms(FI);
8489
8490 // fptoui(uitofp(X)) --> X
8491 // fptoui(sitofp(X)) --> X
8492 // This is safe if the intermediate type has enough bits in its mantissa to
8493 // accurately represent all values of X. For example, do not do this with
8494 // i64->float->i64. This is also safe for sitofp case, because any negative
8495 // 'X' value would cause an undefined result for the fptoui.
8496 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8497 OpI->getOperand(0)->getType() == FI.getType() &&
8498 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8499 OpI->getType()->getFPMantissaWidth())
8500 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008501
8502 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008503}
8504
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008505Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008506 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8507 if (OpI == 0)
8508 return commonCastTransforms(FI);
8509
8510 // fptosi(sitofp(X)) --> X
8511 // fptosi(uitofp(X)) --> X
8512 // This is safe if the intermediate type has enough bits in its mantissa to
8513 // accurately represent all values of X. For example, do not do this with
8514 // i64->float->i64. This is also safe for sitofp case, because any negative
8515 // 'X' value would cause an undefined result for the fptoui.
8516 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8517 OpI->getOperand(0)->getType() == FI.getType() &&
8518 (int)FI.getType()->getPrimitiveSizeInBits() <=
8519 OpI->getType()->getFPMantissaWidth())
8520 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008521
8522 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008523}
8524
8525Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8526 return commonCastTransforms(CI);
8527}
8528
8529Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8530 return commonCastTransforms(CI);
8531}
8532
8533Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008534 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008535}
8536
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008537Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8538 if (Instruction *I = commonCastTransforms(CI))
8539 return I;
8540
8541 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8542 if (!DestPointee->isSized()) return 0;
8543
8544 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8545 ConstantInt *Cst;
8546 Value *X;
8547 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8548 m_ConstantInt(Cst)))) {
8549 // If the source and destination operands have the same type, see if this
8550 // is a single-index GEP.
8551 if (X->getType() == CI.getType()) {
8552 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008553 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008554
8555 // Convert the constant to intptr type.
8556 APInt Offset = Cst->getValue();
8557 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8558
8559 // If Offset is evenly divisible by Size, we can do this xform.
8560 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8561 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008562 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008563 }
8564 }
8565 // TODO: Could handle other cases, e.g. where add is indexing into field of
8566 // struct etc.
8567 } else if (CI.getOperand(0)->hasOneUse() &&
8568 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8569 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8570 // "inttoptr+GEP" instead of "add+intptr".
8571
8572 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008573 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008574
8575 // Convert the constant to intptr type.
8576 APInt Offset = Cst->getValue();
8577 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8578
8579 // If Offset is evenly divisible by Size, we can do this xform.
8580 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8581 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8582
8583 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8584 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008585 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008586 }
8587 }
8588 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008589}
8590
Chris Lattnerd3e28342007-04-27 17:44:50 +00008591Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008592 // If the operands are integer typed then apply the integer transforms,
8593 // otherwise just apply the common ones.
8594 Value *Src = CI.getOperand(0);
8595 const Type *SrcTy = Src->getType();
8596 const Type *DestTy = CI.getType();
8597
Chris Lattner42a75512007-01-15 02:27:26 +00008598 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008599 if (Instruction *Result = commonIntCastTransforms(CI))
8600 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008601 } else if (isa<PointerType>(SrcTy)) {
8602 if (Instruction *I = commonPointerCastTransforms(CI))
8603 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008604 } else {
8605 if (Instruction *Result = commonCastTransforms(CI))
8606 return Result;
8607 }
8608
8609
8610 // Get rid of casts from one type to the same type. These are useless and can
8611 // be replaced by the operand.
8612 if (DestTy == Src->getType())
8613 return ReplaceInstUsesWith(CI, Src);
8614
Reid Spencer3da59db2006-11-27 01:05:10 +00008615 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008616 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8617 const Type *DstElTy = DstPTy->getElementType();
8618 const Type *SrcElTy = SrcPTy->getElementType();
8619
Nate Begeman83ad90a2008-03-31 00:22:16 +00008620 // If the address spaces don't match, don't eliminate the bitcast, which is
8621 // required for changing types.
8622 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8623 return 0;
8624
Chris Lattnerd3e28342007-04-27 17:44:50 +00008625 // If we are casting a malloc or alloca to a pointer to a type of the same
8626 // size, rewrite the allocation instruction to allocate the "right" type.
8627 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8628 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8629 return V;
8630
Chris Lattnerd717c182007-05-05 22:32:24 +00008631 // If the source and destination are pointers, and this cast is equivalent
8632 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008633 // This can enhance SROA and other transforms that want type-safe pointers.
8634 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8635 unsigned NumZeros = 0;
8636 while (SrcElTy != DstElTy &&
8637 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8638 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8639 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8640 ++NumZeros;
8641 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008642
Chris Lattnerd3e28342007-04-27 17:44:50 +00008643 // If we found a path from the src to dest, create the getelementptr now.
8644 if (SrcElTy == DstElTy) {
8645 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008646 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8647 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008648 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008649 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008650
Reid Spencer3da59db2006-11-27 01:05:10 +00008651 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8652 if (SVI->hasOneUse()) {
8653 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8654 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008655 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008656 cast<VectorType>(DestTy)->getNumElements() ==
8657 SVI->getType()->getNumElements() &&
8658 SVI->getType()->getNumElements() ==
8659 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008660 CastInst *Tmp;
8661 // If either of the operands is a cast from CI.getType(), then
8662 // evaluating the shuffle in the casted destination's type will allow
8663 // us to eliminate at least one cast.
8664 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8665 Tmp->getOperand(0)->getType() == DestTy) ||
8666 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8667 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008668 Value *LHS = InsertCastBefore(Instruction::BitCast,
8669 SVI->getOperand(0), DestTy, CI);
8670 Value *RHS = InsertCastBefore(Instruction::BitCast,
8671 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008672 // Return a new shuffle vector. Use the same element ID's, as we
8673 // know the vector types match #elts.
8674 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008675 }
8676 }
8677 }
8678 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008679 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008680}
8681
Chris Lattnere576b912004-04-09 23:46:01 +00008682/// GetSelectFoldableOperands - We want to turn code that looks like this:
8683/// %C = or %A, %B
8684/// %D = select %cond, %C, %A
8685/// into:
8686/// %C = select %cond, %B, 0
8687/// %D = or %A, %C
8688///
8689/// Assuming that the specified instruction is an operand to the select, return
8690/// a bitmask indicating which operands of this instruction are foldable if they
8691/// equal the other incoming value of the select.
8692///
8693static unsigned GetSelectFoldableOperands(Instruction *I) {
8694 switch (I->getOpcode()) {
8695 case Instruction::Add:
8696 case Instruction::Mul:
8697 case Instruction::And:
8698 case Instruction::Or:
8699 case Instruction::Xor:
8700 return 3; // Can fold through either operand.
8701 case Instruction::Sub: // Can only fold on the amount subtracted.
8702 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008703 case Instruction::LShr:
8704 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008705 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008706 default:
8707 return 0; // Cannot fold
8708 }
8709}
8710
8711/// GetSelectFoldableConstant - For the same transformation as the previous
8712/// function, return the identity constant that goes into the select.
8713static Constant *GetSelectFoldableConstant(Instruction *I) {
8714 switch (I->getOpcode()) {
8715 default: assert(0 && "This cannot happen!"); abort();
8716 case Instruction::Add:
8717 case Instruction::Sub:
8718 case Instruction::Or:
8719 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008720 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008721 case Instruction::LShr:
8722 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008723 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008724 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008725 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008726 case Instruction::Mul:
8727 return ConstantInt::get(I->getType(), 1);
8728 }
8729}
8730
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008731/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8732/// have the same opcode and only one use each. Try to simplify this.
8733Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8734 Instruction *FI) {
8735 if (TI->getNumOperands() == 1) {
8736 // If this is a non-volatile load or a cast from the same type,
8737 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008738 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008739 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8740 return 0;
8741 } else {
8742 return 0; // unknown unary op.
8743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008744
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008745 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008746 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8747 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008748 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008749 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008750 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008751 }
8752
Reid Spencer832254e2007-02-02 02:16:23 +00008753 // Only handle binary operators here.
8754 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008755 return 0;
8756
8757 // Figure out if the operations have any operands in common.
8758 Value *MatchOp, *OtherOpT, *OtherOpF;
8759 bool MatchIsOpZero;
8760 if (TI->getOperand(0) == FI->getOperand(0)) {
8761 MatchOp = TI->getOperand(0);
8762 OtherOpT = TI->getOperand(1);
8763 OtherOpF = FI->getOperand(1);
8764 MatchIsOpZero = true;
8765 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8766 MatchOp = TI->getOperand(1);
8767 OtherOpT = TI->getOperand(0);
8768 OtherOpF = FI->getOperand(0);
8769 MatchIsOpZero = false;
8770 } else if (!TI->isCommutative()) {
8771 return 0;
8772 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8773 MatchOp = TI->getOperand(0);
8774 OtherOpT = TI->getOperand(1);
8775 OtherOpF = FI->getOperand(0);
8776 MatchIsOpZero = true;
8777 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8778 MatchOp = TI->getOperand(1);
8779 OtherOpT = TI->getOperand(0);
8780 OtherOpF = FI->getOperand(1);
8781 MatchIsOpZero = true;
8782 } else {
8783 return 0;
8784 }
8785
8786 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008787 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8788 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008789 InsertNewInstBefore(NewSI, SI);
8790
8791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8792 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008793 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008794 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008795 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008796 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008797 assert(0 && "Shouldn't get here");
8798 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008799}
8800
Dan Gohman81b28ce2008-09-16 18:46:06 +00008801/// visitSelectInstWithICmp - Visit a SelectInst that has an
8802/// ICmpInst as its first operand.
8803///
8804Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8805 ICmpInst *ICI) {
8806 bool Changed = false;
8807 ICmpInst::Predicate Pred = ICI->getPredicate();
8808 Value *CmpLHS = ICI->getOperand(0);
8809 Value *CmpRHS = ICI->getOperand(1);
8810 Value *TrueVal = SI.getTrueValue();
8811 Value *FalseVal = SI.getFalseValue();
8812
8813 // Check cases where the comparison is with a constant that
8814 // can be adjusted to fit the min/max idiom. We may edit ICI in
8815 // place here, so make sure the select is the only user.
8816 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008817 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008818 switch (Pred) {
8819 default: break;
8820 case ICmpInst::ICMP_ULT:
8821 case ICmpInst::ICMP_SLT: {
8822 // X < MIN ? T : F --> F
8823 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8824 return ReplaceInstUsesWith(SI, FalseVal);
8825 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8826 Constant *AdjustedRHS = SubOne(CI);
8827 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8828 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8829 Pred = ICmpInst::getSwappedPredicate(Pred);
8830 CmpRHS = AdjustedRHS;
8831 std::swap(FalseVal, TrueVal);
8832 ICI->setPredicate(Pred);
8833 ICI->setOperand(1, CmpRHS);
8834 SI.setOperand(1, TrueVal);
8835 SI.setOperand(2, FalseVal);
8836 Changed = true;
8837 }
8838 break;
8839 }
8840 case ICmpInst::ICMP_UGT:
8841 case ICmpInst::ICMP_SGT: {
8842 // X > MAX ? T : F --> F
8843 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8844 return ReplaceInstUsesWith(SI, FalseVal);
8845 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8846 Constant *AdjustedRHS = AddOne(CI);
8847 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8848 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8849 Pred = ICmpInst::getSwappedPredicate(Pred);
8850 CmpRHS = AdjustedRHS;
8851 std::swap(FalseVal, TrueVal);
8852 ICI->setPredicate(Pred);
8853 ICI->setOperand(1, CmpRHS);
8854 SI.setOperand(1, TrueVal);
8855 SI.setOperand(2, FalseVal);
8856 Changed = true;
8857 }
8858 break;
8859 }
8860 }
8861
Dan Gohman1975d032008-10-30 20:40:10 +00008862 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8863 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008864 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008865 if (match(TrueVal, m_ConstantInt<-1>()) &&
8866 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008867 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008868 else if (match(TrueVal, m_ConstantInt<0>()) &&
8869 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008870 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8871
Dan Gohman1975d032008-10-30 20:40:10 +00008872 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8873 // If we are just checking for a icmp eq of a single bit and zext'ing it
8874 // to an integer, then shift the bit to the appropriate place and then
8875 // cast to integer to avoid the comparison.
8876 const APInt &Op1CV = CI->getValue();
8877
8878 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8879 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8880 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008881 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008882 Value *In = ICI->getOperand(0);
8883 Value *Sh = ConstantInt::get(In->getType(),
8884 In->getType()->getPrimitiveSizeInBits()-1);
8885 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8886 In->getName()+".lobit"),
8887 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008888 if (In->getType() != SI.getType())
8889 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008890 true/*SExt*/, "tmp", ICI);
8891
8892 if (Pred == ICmpInst::ICMP_SGT)
8893 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8894 In->getName()+".not"), *ICI);
8895
8896 return ReplaceInstUsesWith(SI, In);
8897 }
8898 }
8899 }
8900
Dan Gohman81b28ce2008-09-16 18:46:06 +00008901 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8902 // Transform (X == Y) ? X : Y -> Y
8903 if (Pred == ICmpInst::ICMP_EQ)
8904 return ReplaceInstUsesWith(SI, FalseVal);
8905 // Transform (X != Y) ? X : Y -> X
8906 if (Pred == ICmpInst::ICMP_NE)
8907 return ReplaceInstUsesWith(SI, TrueVal);
8908 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8909
8910 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8911 // Transform (X == Y) ? Y : X -> X
8912 if (Pred == ICmpInst::ICMP_EQ)
8913 return ReplaceInstUsesWith(SI, FalseVal);
8914 // Transform (X != Y) ? Y : X -> Y
8915 if (Pred == ICmpInst::ICMP_NE)
8916 return ReplaceInstUsesWith(SI, TrueVal);
8917 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8918 }
8919
8920 /// NOTE: if we wanted to, this is where to detect integer ABS
8921
8922 return Changed ? &SI : 0;
8923}
8924
Chris Lattner3d69f462004-03-12 05:52:32 +00008925Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008926 Value *CondVal = SI.getCondition();
8927 Value *TrueVal = SI.getTrueValue();
8928 Value *FalseVal = SI.getFalseValue();
8929
8930 // select true, X, Y -> X
8931 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008932 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008933 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008934
8935 // select C, X, X -> X
8936 if (TrueVal == FalseVal)
8937 return ReplaceInstUsesWith(SI, TrueVal);
8938
Chris Lattnere87597f2004-10-16 18:11:37 +00008939 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8940 return ReplaceInstUsesWith(SI, FalseVal);
8941 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8942 return ReplaceInstUsesWith(SI, TrueVal);
8943 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8944 if (isa<Constant>(TrueVal))
8945 return ReplaceInstUsesWith(SI, TrueVal);
8946 else
8947 return ReplaceInstUsesWith(SI, FalseVal);
8948 }
8949
Reid Spencer4fe16d62007-01-11 18:21:29 +00008950 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008951 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008952 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008953 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008954 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008955 } else {
8956 // Change: A = select B, false, C --> A = and !B, C
8957 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008958 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008959 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008960 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008961 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008962 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008963 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008964 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008965 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008966 } else {
8967 // Change: A = select B, C, true --> A = or !B, C
8968 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008969 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008970 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008971 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008972 }
8973 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008974
8975 // select a, b, a -> a&b
8976 // select a, a, b -> a|b
8977 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008978 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008979 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008980 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008981 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008982
Chris Lattner2eefe512004-04-09 19:05:30 +00008983 // Selecting between two integer constants?
8984 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8985 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008986 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008987 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008988 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008989 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008990 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008991 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008992 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008993 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008994 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008995 }
Chris Lattner457dd822004-06-09 07:59:58 +00008996
Reid Spencere4d87aa2006-12-23 06:05:41 +00008997 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008998
Reid Spencere4d87aa2006-12-23 06:05:41 +00008999 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009000 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009001 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009002 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009003 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009004 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009005 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00009006 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009007 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009008 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009009 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009010 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009011
9012 // Then cast to the appropriate width.
9013 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009014 }
9015 }
9016
9017
9018 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009019 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009020 // non-constant value, eliminate this whole mess. This corresponds to
9021 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009022 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009023 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009024 cast<Constant>(IC->getOperand(1))->isNullValue())
9025 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9026 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009027 isa<ConstantInt>(ICA->getOperand(1)) &&
9028 (ICA->getOperand(1) == TrueValC ||
9029 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009030 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9031 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009032 // know whether we have a icmp_ne or icmp_eq and whether the
9033 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009034 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009035 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009036 Value *V = ICA;
9037 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009038 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009039 Instruction::Xor, V, ICA->getOperand(1)), SI);
9040 return ReplaceInstUsesWith(SI, V);
9041 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009042 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009043 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009044
9045 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009046 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9047 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009048 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009049 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9050 // This is not safe in general for floating point:
9051 // consider X== -0, Y== +0.
9052 // It becomes safe if either operand is a nonzero constant.
9053 ConstantFP *CFPt, *CFPf;
9054 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9055 !CFPt->getValueAPF().isZero()) ||
9056 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9057 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009058 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009059 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009060 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009061 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009062 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009063 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009064
Reid Spencere4d87aa2006-12-23 06:05:41 +00009065 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009066 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009067 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9068 // This is not safe in general for floating point:
9069 // consider X== -0, Y== +0.
9070 // It becomes safe if either operand is a nonzero constant.
9071 ConstantFP *CFPt, *CFPf;
9072 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9073 !CFPt->getValueAPF().isZero()) ||
9074 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9075 !CFPf->getValueAPF().isZero()))
9076 return ReplaceInstUsesWith(SI, FalseVal);
9077 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009078 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009079 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9080 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009081 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009082 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009083 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009084 }
9085
9086 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009087 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9088 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9089 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009090
Chris Lattner87875da2005-01-13 22:52:24 +00009091 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9092 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9093 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009094 Instruction *AddOp = 0, *SubOp = 0;
9095
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009096 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9097 if (TI->getOpcode() == FI->getOpcode())
9098 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9099 return IV;
9100
9101 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9102 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009103 if (TI->getOpcode() == Instruction::Sub &&
9104 FI->getOpcode() == Instruction::Add) {
9105 AddOp = FI; SubOp = TI;
9106 } else if (FI->getOpcode() == Instruction::Sub &&
9107 TI->getOpcode() == Instruction::Add) {
9108 AddOp = TI; SubOp = FI;
9109 }
9110
9111 if (AddOp) {
9112 Value *OtherAddOp = 0;
9113 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9114 OtherAddOp = AddOp->getOperand(1);
9115 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9116 OtherAddOp = AddOp->getOperand(0);
9117 }
9118
9119 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009120 // So at this point we know we have (Y -> OtherAddOp):
9121 // select C, (add X, Y), (sub X, Z)
9122 Value *NegVal; // Compute -Z
9123 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9124 NegVal = ConstantExpr::getNeg(C);
9125 } else {
9126 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009127 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009128 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009129
9130 Value *NewTrueOp = OtherAddOp;
9131 Value *NewFalseOp = NegVal;
9132 if (AddOp != TI)
9133 std::swap(NewTrueOp, NewFalseOp);
9134 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009135 SelectInst::Create(CondVal, NewTrueOp,
9136 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009137
9138 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009139 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009140 }
9141 }
9142 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009143
Chris Lattnere576b912004-04-09 23:46:01 +00009144 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009145 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009146 // See the comment above GetSelectFoldableOperands for a description of the
9147 // transformation we are doing here.
9148 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9149 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9150 !isa<Constant>(FalseVal))
9151 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9152 unsigned OpToFold = 0;
9153 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9154 OpToFold = 1;
9155 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9156 OpToFold = 2;
9157 }
9158
9159 if (OpToFold) {
9160 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009161 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009162 SelectInst::Create(SI.getCondition(),
9163 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009164 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009165 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009167 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009168 else {
9169 assert(0 && "Unknown instruction!!");
9170 }
9171 }
9172 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009173
Chris Lattnere576b912004-04-09 23:46:01 +00009174 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9175 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9176 !isa<Constant>(TrueVal))
9177 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9178 unsigned OpToFold = 0;
9179 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9180 OpToFold = 1;
9181 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9182 OpToFold = 2;
9183 }
9184
9185 if (OpToFold) {
9186 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009187 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009188 SelectInst::Create(SI.getCondition(), C,
9189 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009190 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009191 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009192 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009193 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009194 else
Chris Lattnere576b912004-04-09 23:46:01 +00009195 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009196 }
9197 }
9198 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009199
9200 if (BinaryOperator::isNot(CondVal)) {
9201 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9202 SI.setOperand(1, FalseVal);
9203 SI.setOperand(2, TrueVal);
9204 return &SI;
9205 }
9206
Chris Lattner3d69f462004-03-12 05:52:32 +00009207 return 0;
9208}
9209
Dan Gohmaneee962e2008-04-10 18:43:06 +00009210/// EnforceKnownAlignment - If the specified pointer points to an object that
9211/// we control, modify the object's alignment to PrefAlign. This isn't
9212/// often possible though. If alignment is important, a more reliable approach
9213/// is to simply align all global variables and allocation instructions to
9214/// their preferred alignment from the beginning.
9215///
9216static unsigned EnforceKnownAlignment(Value *V,
9217 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009218
Dan Gohmaneee962e2008-04-10 18:43:06 +00009219 User *U = dyn_cast<User>(V);
9220 if (!U) return Align;
9221
9222 switch (getOpcode(U)) {
9223 default: break;
9224 case Instruction::BitCast:
9225 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9226 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009227 // If all indexes are zero, it is just the alignment of the base pointer.
9228 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009229 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009230 if (!isa<Constant>(*i) ||
9231 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009232 AllZeroOperands = false;
9233 break;
9234 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009235
9236 if (AllZeroOperands) {
9237 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009238 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009239 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009240 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009241 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009242 }
9243
9244 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9245 // If there is a large requested alignment and we can, bump up the alignment
9246 // of the global.
9247 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009248 if (GV->getAlignment() >= PrefAlign)
9249 Align = GV->getAlignment();
9250 else {
9251 GV->setAlignment(PrefAlign);
9252 Align = PrefAlign;
9253 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009254 }
9255 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9256 // If there is a requested alignment and if this is an alloca, round up. We
9257 // don't do this for malloc, because some systems can't respect the request.
9258 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009259 if (AI->getAlignment() >= PrefAlign)
9260 Align = AI->getAlignment();
9261 else {
9262 AI->setAlignment(PrefAlign);
9263 Align = PrefAlign;
9264 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009265 }
9266 }
9267
9268 return Align;
9269}
9270
9271/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9272/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9273/// and it is more than the alignment of the ultimate object, see if we can
9274/// increase the alignment of the ultimate object, making this check succeed.
9275unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9276 unsigned PrefAlign) {
9277 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9278 sizeof(PrefAlign) * CHAR_BIT;
9279 APInt Mask = APInt::getAllOnesValue(BitWidth);
9280 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9281 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9282 unsigned TrailZ = KnownZero.countTrailingOnes();
9283 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9284
9285 if (PrefAlign > Align)
9286 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9287
9288 // We don't need to make any adjustment.
9289 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009290}
9291
Chris Lattnerf497b022008-01-13 23:50:23 +00009292Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009293 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009294 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009295 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9296 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9297
9298 if (CopyAlign < MinAlign) {
9299 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9300 return MI;
9301 }
9302
9303 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9304 // load/store.
9305 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9306 if (MemOpLength == 0) return 0;
9307
Chris Lattner37ac6082008-01-14 00:28:35 +00009308 // Source and destination pointer types are always "i8*" for intrinsic. See
9309 // if the size is something we can handle with a single primitive load/store.
9310 // A single load+store correctly handles overlapping memory in the memmove
9311 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009312 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009313 if (Size == 0) return MI; // Delete this mem transfer.
9314
9315 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009316 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009317
Chris Lattner37ac6082008-01-14 00:28:35 +00009318 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009319 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009320
9321 // Memcpy forces the use of i8* for the source and destination. That means
9322 // that if you're using memcpy to move one double around, you'll get a cast
9323 // from double* to i8*. We'd much rather use a double load+store rather than
9324 // an i64 load+store, here because this improves the odds that the source or
9325 // dest address will be promotable. See if we can find a better type than the
9326 // integer datatype.
9327 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9328 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9329 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9330 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9331 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009332 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009333 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9334 if (STy->getNumElements() == 1)
9335 SrcETy = STy->getElementType(0);
9336 else
9337 break;
9338 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9339 if (ATy->getNumElements() == 1)
9340 SrcETy = ATy->getElementType();
9341 else
9342 break;
9343 } else
9344 break;
9345 }
9346
Dan Gohman8f8e2692008-05-23 01:52:21 +00009347 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009348 NewPtrTy = PointerType::getUnqual(SrcETy);
9349 }
9350 }
9351
9352
Chris Lattnerf497b022008-01-13 23:50:23 +00009353 // If the memcpy/memmove provides better alignment info than we can
9354 // infer, use it.
9355 SrcAlign = std::max(SrcAlign, CopyAlign);
9356 DstAlign = std::max(DstAlign, CopyAlign);
9357
9358 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9359 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009360 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9361 InsertNewInstBefore(L, *MI);
9362 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9363
9364 // Set the size of the copy to 0, it will be deleted on the next iteration.
9365 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9366 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009367}
Chris Lattner3d69f462004-03-12 05:52:32 +00009368
Chris Lattner69ea9d22008-04-30 06:39:11 +00009369Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9370 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9371 if (MI->getAlignment()->getZExtValue() < Alignment) {
9372 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9373 return MI;
9374 }
9375
9376 // Extract the length and alignment and fill if they are constant.
9377 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9378 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9379 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9380 return 0;
9381 uint64_t Len = LenC->getZExtValue();
9382 Alignment = MI->getAlignment()->getZExtValue();
9383
9384 // If the length is zero, this is a no-op
9385 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9386
9387 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9388 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9389 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9390
9391 Value *Dest = MI->getDest();
9392 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9393
9394 // Alignment 0 is identity for alignment 1 for memset, but not store.
9395 if (Alignment == 0) Alignment = 1;
9396
9397 // Extract the fill value and store.
9398 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9399 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9400 Alignment), *MI);
9401
9402 // Set the size of the copy to 0, it will be deleted on the next iteration.
9403 MI->setLength(Constant::getNullValue(LenC->getType()));
9404 return MI;
9405 }
9406
9407 return 0;
9408}
9409
9410
Chris Lattner8b0ea312006-01-13 20:11:04 +00009411/// visitCallInst - CallInst simplification. This mostly only handles folding
9412/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9413/// the heavy lifting.
9414///
Chris Lattner9fe38862003-06-19 17:00:31 +00009415Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009416 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9417 if (!II) return visitCallSite(&CI);
9418
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009419 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9420 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009421 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009422 bool Changed = false;
9423
9424 // memmove/cpy/set of zero bytes is a noop.
9425 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9426 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9427
Chris Lattner35b9e482004-10-12 04:52:52 +00009428 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009429 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009430 // Replace the instruction with just byte operations. We would
9431 // transform other cases to loads/stores, but we don't know if
9432 // alignment is sufficient.
9433 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009434 }
9435
Chris Lattner35b9e482004-10-12 04:52:52 +00009436 // If we have a memmove and the source operation is a constant global,
9437 // then the source and dest pointers can't alias, so we can change this
9438 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009439 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009440 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9441 if (GVSrc->isConstant()) {
9442 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009443 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9444 const Type *Tys[1];
9445 Tys[0] = CI.getOperand(3)->getType();
9446 CI.setOperand(0,
9447 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009448 Changed = true;
9449 }
Chris Lattnera935db82008-05-28 05:30:41 +00009450
9451 // memmove(x,x,size) -> noop.
9452 if (MMI->getSource() == MMI->getDest())
9453 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009454 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009455
Chris Lattner95a959d2006-03-06 20:18:44 +00009456 // If we can determine a pointer alignment that is bigger than currently
9457 // set, update the alignment.
9458 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009459 if (Instruction *I = SimplifyMemTransfer(MI))
9460 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009461 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9462 if (Instruction *I = SimplifyMemSet(MSI))
9463 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009464 }
9465
Chris Lattner8b0ea312006-01-13 20:11:04 +00009466 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009467 }
9468
9469 switch (II->getIntrinsicID()) {
9470 default: break;
9471 case Intrinsic::bswap:
9472 // bswap(bswap(x)) -> x
9473 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9474 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9475 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9476 break;
9477 case Intrinsic::ppc_altivec_lvx:
9478 case Intrinsic::ppc_altivec_lvxl:
9479 case Intrinsic::x86_sse_loadu_ps:
9480 case Intrinsic::x86_sse2_loadu_pd:
9481 case Intrinsic::x86_sse2_loadu_dq:
9482 // Turn PPC lvx -> load if the pointer is known aligned.
9483 // Turn X86 loadups -> load if the pointer is known aligned.
9484 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9485 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9486 PointerType::getUnqual(II->getType()),
9487 CI);
9488 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009489 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009490 break;
9491 case Intrinsic::ppc_altivec_stvx:
9492 case Intrinsic::ppc_altivec_stvxl:
9493 // Turn stvx -> store if the pointer is known aligned.
9494 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9495 const Type *OpPtrTy =
9496 PointerType::getUnqual(II->getOperand(1)->getType());
9497 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9498 return new StoreInst(II->getOperand(1), Ptr);
9499 }
9500 break;
9501 case Intrinsic::x86_sse_storeu_ps:
9502 case Intrinsic::x86_sse2_storeu_pd:
9503 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009504 // Turn X86 storeu -> store if the pointer is known aligned.
9505 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9506 const Type *OpPtrTy =
9507 PointerType::getUnqual(II->getOperand(2)->getType());
9508 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9509 return new StoreInst(II->getOperand(2), Ptr);
9510 }
9511 break;
9512
9513 case Intrinsic::x86_sse_cvttss2si: {
9514 // These intrinsics only demands the 0th element of its input vector. If
9515 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009516 unsigned VWidth =
9517 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9518 APInt DemandedElts(VWidth, 1);
9519 APInt UndefElts(VWidth, 0);
9520 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009521 UndefElts)) {
9522 II->setOperand(1, V);
9523 return II;
9524 }
9525 break;
9526 }
9527
9528 case Intrinsic::ppc_altivec_vperm:
9529 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9530 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9531 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009532
Chris Lattner0521e3c2008-06-18 04:33:20 +00009533 // Check that all of the elements are integer constants or undefs.
9534 bool AllEltsOk = true;
9535 for (unsigned i = 0; i != 16; ++i) {
9536 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9537 !isa<UndefValue>(Mask->getOperand(i))) {
9538 AllEltsOk = false;
9539 break;
9540 }
9541 }
9542
9543 if (AllEltsOk) {
9544 // Cast the input vectors to byte vectors.
9545 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9546 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9547 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009548
Chris Lattner0521e3c2008-06-18 04:33:20 +00009549 // Only extract each element once.
9550 Value *ExtractedElts[32];
9551 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9552
Chris Lattnere2ed0572006-04-06 19:19:17 +00009553 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009554 if (isa<UndefValue>(Mask->getOperand(i)))
9555 continue;
9556 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9557 Idx &= 31; // Match the hardware behavior.
9558
9559 if (ExtractedElts[Idx] == 0) {
9560 Instruction *Elt =
9561 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9562 InsertNewInstBefore(Elt, CI);
9563 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009564 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009565
Chris Lattner0521e3c2008-06-18 04:33:20 +00009566 // Insert this value into the result vector.
9567 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9568 i, "tmp");
9569 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009570 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009571 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009572 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009573 }
9574 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009575
Chris Lattner0521e3c2008-06-18 04:33:20 +00009576 case Intrinsic::stackrestore: {
9577 // If the save is right next to the restore, remove the restore. This can
9578 // happen when variable allocas are DCE'd.
9579 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9580 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9581 BasicBlock::iterator BI = SS;
9582 if (&*++BI == II)
9583 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009584 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009585 }
9586
9587 // Scan down this block to see if there is another stack restore in the
9588 // same block without an intervening call/alloca.
9589 BasicBlock::iterator BI = II;
9590 TerminatorInst *TI = II->getParent()->getTerminator();
9591 bool CannotRemove = false;
9592 for (++BI; &*BI != TI; ++BI) {
9593 if (isa<AllocaInst>(BI)) {
9594 CannotRemove = true;
9595 break;
9596 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009597 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9598 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9599 // If there is a stackrestore below this one, remove this one.
9600 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9601 return EraseInstFromFunction(CI);
9602 // Otherwise, ignore the intrinsic.
9603 } else {
9604 // If we found a non-intrinsic call, we can't remove the stack
9605 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009606 CannotRemove = true;
9607 break;
9608 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009609 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009610 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009611
9612 // If the stack restore is in a return/unwind block and if there are no
9613 // allocas or calls between the restore and the return, nuke the restore.
9614 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9615 return EraseInstFromFunction(CI);
9616 break;
9617 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009618 }
9619
Chris Lattner8b0ea312006-01-13 20:11:04 +00009620 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009621}
9622
9623// InvokeInst simplification
9624//
9625Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009626 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009627}
9628
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009629/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9630/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009631static bool isSafeToEliminateVarargsCast(const CallSite CS,
9632 const CastInst * const CI,
9633 const TargetData * const TD,
9634 const int ix) {
9635 if (!CI->isLosslessCast())
9636 return false;
9637
9638 // The size of ByVal arguments is derived from the type, so we
9639 // can't change to a type with a different size. If the size were
9640 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009641 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009642 return true;
9643
9644 const Type* SrcTy =
9645 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9646 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9647 if (!SrcTy->isSized() || !DstTy->isSized())
9648 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009649 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009650 return false;
9651 return true;
9652}
9653
Chris Lattnera44d8a22003-10-07 22:32:43 +00009654// visitCallSite - Improvements for call and invoke instructions.
9655//
9656Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009657 bool Changed = false;
9658
9659 // If the callee is a constexpr cast of a function, attempt to move the cast
9660 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009661 if (transformConstExprCastCall(CS)) return 0;
9662
Chris Lattner6c266db2003-10-07 22:54:13 +00009663 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009664
Chris Lattner08b22ec2005-05-13 07:09:09 +00009665 if (Function *CalleeF = dyn_cast<Function>(Callee))
9666 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9667 Instruction *OldCall = CS.getInstruction();
9668 // If the call and callee calling conventions don't match, this call must
9669 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009670 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009671 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9672 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009673 if (!OldCall->use_empty())
9674 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9675 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9676 return EraseInstFromFunction(*OldCall);
9677 return 0;
9678 }
9679
Chris Lattner17be6352004-10-18 02:59:09 +00009680 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9681 // This instruction is not reachable, just remove it. We insert a store to
9682 // undef so that we know that this code is not reachable, despite the fact
9683 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009684 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009685 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009686 CS.getInstruction());
9687
9688 if (!CS.getInstruction()->use_empty())
9689 CS.getInstruction()->
9690 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9691
9692 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9693 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009694 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9695 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009696 }
Chris Lattner17be6352004-10-18 02:59:09 +00009697 return EraseInstFromFunction(*CS.getInstruction());
9698 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009699
Duncan Sandscdb6d922007-09-17 10:26:40 +00009700 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9701 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9702 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9703 return transformCallThroughTrampoline(CS);
9704
Chris Lattner6c266db2003-10-07 22:54:13 +00009705 const PointerType *PTy = cast<PointerType>(Callee->getType());
9706 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9707 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009708 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009709 // See if we can optimize any arguments passed through the varargs area of
9710 // the call.
9711 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009712 E = CS.arg_end(); I != E; ++I, ++ix) {
9713 CastInst *CI = dyn_cast<CastInst>(*I);
9714 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9715 *I = CI->getOperand(0);
9716 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009717 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009718 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009719 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009720
Duncan Sandsf0c33542007-12-19 21:13:37 +00009721 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009722 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009723 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009724 Changed = true;
9725 }
9726
Chris Lattner6c266db2003-10-07 22:54:13 +00009727 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009728}
9729
Chris Lattner9fe38862003-06-19 17:00:31 +00009730// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9731// attempt to move the cast to the arguments of the call/invoke.
9732//
9733bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9734 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9735 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009736 if (CE->getOpcode() != Instruction::BitCast ||
9737 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009738 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009739 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009740 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009741 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009742
9743 // Okay, this is a cast from a function to a different type. Unless doing so
9744 // would cause a type conversion of one of our arguments, change this call to
9745 // be a direct call with arguments casted to the appropriate types.
9746 //
9747 const FunctionType *FT = Callee->getFunctionType();
9748 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009749 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009750
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009751 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009752 return false; // TODO: Handle multiple return values.
9753
Chris Lattnerf78616b2004-01-14 06:06:08 +00009754 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009755 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009756 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009757 // Conversion is ok if changing from one pointer type to another or from
9758 // a pointer to an integer of the same size.
9759 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009760 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009761 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009762
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009763 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009764 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009765 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009766 return false; // Cannot transform this return value.
9767
Chris Lattner58d74912008-03-12 17:45:29 +00009768 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009769 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009770 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009771 return false; // Attribute not compatible with transformed value.
9772 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009773
Chris Lattnerf78616b2004-01-14 06:06:08 +00009774 // If the callsite is an invoke instruction, and the return value is used by
9775 // a PHI node in a successor, we cannot change the return type of the call
9776 // because there is no place to put the cast instruction (without breaking
9777 // the critical edge). Bail out in this case.
9778 if (!Caller->use_empty())
9779 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9780 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9781 UI != E; ++UI)
9782 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9783 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009784 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009785 return false;
9786 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009787
9788 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9789 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009790
Chris Lattner9fe38862003-06-19 17:00:31 +00009791 CallSite::arg_iterator AI = CS.arg_begin();
9792 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9793 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009794 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009795
9796 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009797 return false; // Cannot transform this parameter value.
9798
Devang Patel19c87462008-09-26 22:53:05 +00009799 if (CallerPAL.getParamAttributes(i + 1)
9800 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009801 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009802
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009803 // Converting from one pointer type to another or between a pointer and an
9804 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009805 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009806 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9807 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009808 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009809 }
9810
9811 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009812 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009813 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009814
Chris Lattner58d74912008-03-12 17:45:29 +00009815 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9816 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009817 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009818 // won't be dropping them. Check that these extra arguments have attributes
9819 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009820 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9821 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009822 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009823 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009824 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009825 return false;
9826 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009827
Chris Lattner9fe38862003-06-19 17:00:31 +00009828 // Okay, we decided that this is a safe thing to do: go ahead and start
9829 // inserting cast instructions as necessary...
9830 std::vector<Value*> Args;
9831 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009832 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009833 attrVec.reserve(NumCommonArgs);
9834
9835 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009836 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009837
9838 // If the return value is not being used, the type may not be compatible
9839 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009840 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009841
9842 // Add the new return attributes.
9843 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009844 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009845
9846 AI = CS.arg_begin();
9847 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9848 const Type *ParamTy = FT->getParamType(i);
9849 if ((*AI)->getType() == ParamTy) {
9850 Args.push_back(*AI);
9851 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009852 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009853 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009854 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009855 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009856 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009857
9858 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009859 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009860 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009861 }
9862
9863 // If the function takes more arguments than the call was taking, add them
9864 // now...
9865 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9866 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9867
9868 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009869 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009870 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009871 cerr << "WARNING: While resolving call to function '"
9872 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009873 } else {
9874 // Add all of the arguments in their promoted form to the arg list...
9875 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9876 const Type *PTy = getPromotedType((*AI)->getType());
9877 if (PTy != (*AI)->getType()) {
9878 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009879 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9880 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009881 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009882 InsertNewInstBefore(Cast, *Caller);
9883 Args.push_back(Cast);
9884 } else {
9885 Args.push_back(*AI);
9886 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009887
Duncan Sandse1e520f2008-01-13 08:02:44 +00009888 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009889 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009890 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009891 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009892 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009893 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009894
Devang Patel19c87462008-09-26 22:53:05 +00009895 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9896 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9897
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009898 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009899 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009900
Devang Patel05988662008-09-25 21:00:45 +00009901 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009902
Chris Lattner9fe38862003-06-19 17:00:31 +00009903 Instruction *NC;
9904 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009905 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009906 Args.begin(), Args.end(),
9907 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009908 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009909 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009910 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009911 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9912 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009913 CallInst *CI = cast<CallInst>(Caller);
9914 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009915 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009916 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009917 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009918 }
9919
Chris Lattner6934a042007-02-11 01:23:03 +00009920 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009921 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009922 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009923 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009924 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009925 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009926 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009927
9928 // If this is an invoke instruction, we should insert it after the first
9929 // non-phi, instruction in the normal successor block.
9930 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009931 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009932 InsertNewInstBefore(NC, *I);
9933 } else {
9934 // Otherwise, it's a call, just insert cast right after the call instr
9935 InsertNewInstBefore(NC, *Caller);
9936 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009937 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009938 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009939 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009940 }
9941 }
9942
9943 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9944 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009945 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009946 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009947 return true;
9948}
9949
Duncan Sandscdb6d922007-09-17 10:26:40 +00009950// transformCallThroughTrampoline - Turn a call to a function created by the
9951// init_trampoline intrinsic into a direct call to the underlying function.
9952//
9953Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9954 Value *Callee = CS.getCalledValue();
9955 const PointerType *PTy = cast<PointerType>(Callee->getType());
9956 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009957 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009958
9959 // If the call already has the 'nest' attribute somewhere then give up -
9960 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009961 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009962 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009963
9964 IntrinsicInst *Tramp =
9965 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9966
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009967 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009968 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9969 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9970
Devang Patel05988662008-09-25 21:00:45 +00009971 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009972 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009973 unsigned NestIdx = 1;
9974 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009975 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009976
9977 // Look for a parameter marked with the 'nest' attribute.
9978 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9979 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009980 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009981 // Record the parameter type and any other attributes.
9982 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009983 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009984 break;
9985 }
9986
9987 if (NestTy) {
9988 Instruction *Caller = CS.getInstruction();
9989 std::vector<Value*> NewArgs;
9990 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9991
Devang Patel05988662008-09-25 21:00:45 +00009992 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009993 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009994
Duncan Sandscdb6d922007-09-17 10:26:40 +00009995 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009996 // mean appending it. Likewise for attributes.
9997
Devang Patel19c87462008-09-26 22:53:05 +00009998 // Add any result attributes.
9999 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010000 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010001
Duncan Sandscdb6d922007-09-17 10:26:40 +000010002 {
10003 unsigned Idx = 1;
10004 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10005 do {
10006 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010007 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010008 Value *NestVal = Tramp->getOperand(3);
10009 if (NestVal->getType() != NestTy)
10010 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10011 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010012 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010013 }
10014
10015 if (I == E)
10016 break;
10017
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010018 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010019 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010020 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010021 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010022 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010023
10024 ++Idx, ++I;
10025 } while (1);
10026 }
10027
Devang Patel19c87462008-09-26 22:53:05 +000010028 // Add any function attributes.
10029 if (Attributes Attr = Attrs.getFnAttributes())
10030 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10031
Duncan Sandscdb6d922007-09-17 10:26:40 +000010032 // The trampoline may have been bitcast to a bogus type (FTy).
10033 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010034 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010035
Duncan Sandscdb6d922007-09-17 10:26:40 +000010036 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010037 NewTypes.reserve(FTy->getNumParams()+1);
10038
Duncan Sandscdb6d922007-09-17 10:26:40 +000010039 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010040 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010041 {
10042 unsigned Idx = 1;
10043 FunctionType::param_iterator I = FTy->param_begin(),
10044 E = FTy->param_end();
10045
10046 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010047 if (Idx == NestIdx)
10048 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010049 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010050
10051 if (I == E)
10052 break;
10053
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010054 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010055 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010056
10057 ++Idx, ++I;
10058 } while (1);
10059 }
10060
10061 // Replace the trampoline call with a direct call. Let the generic
10062 // code sort out any function type mismatches.
10063 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010064 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010065 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10066 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010067 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010068
10069 Instruction *NewCaller;
10070 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010071 NewCaller = InvokeInst::Create(NewCallee,
10072 II->getNormalDest(), II->getUnwindDest(),
10073 NewArgs.begin(), NewArgs.end(),
10074 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010075 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010076 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010077 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010078 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10079 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010080 if (cast<CallInst>(Caller)->isTailCall())
10081 cast<CallInst>(NewCaller)->setTailCall();
10082 cast<CallInst>(NewCaller)->
10083 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010084 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010085 }
10086 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10087 Caller->replaceAllUsesWith(NewCaller);
10088 Caller->eraseFromParent();
10089 RemoveFromWorkList(Caller);
10090 return 0;
10091 }
10092 }
10093
10094 // Replace the trampoline call with a direct call. Since there is no 'nest'
10095 // parameter, there is no need to adjust the argument list. Let the generic
10096 // code sort out any function type mismatches.
10097 Constant *NewCallee =
10098 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10099 CS.setCalledFunction(NewCallee);
10100 return CS.getInstruction();
10101}
10102
Chris Lattner7da52b22006-11-01 04:51:18 +000010103/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10104/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10105/// and a single binop.
10106Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10107 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010108 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010109 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010110 Value *LHSVal = FirstInst->getOperand(0);
10111 Value *RHSVal = FirstInst->getOperand(1);
10112
10113 const Type *LHSType = LHSVal->getType();
10114 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010115
10116 // Scan to see if all operands are the same opcode, all have one use, and all
10117 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010118 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010119 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010120 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010121 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010122 // types or GEP's with different index types.
10123 I->getOperand(0)->getType() != LHSType ||
10124 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010125 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010126
10127 // If they are CmpInst instructions, check their predicates
10128 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10129 if (cast<CmpInst>(I)->getPredicate() !=
10130 cast<CmpInst>(FirstInst)->getPredicate())
10131 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010132
10133 // Keep track of which operand needs a phi node.
10134 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10135 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010136 }
10137
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010138 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010139
Chris Lattner7da52b22006-11-01 04:51:18 +000010140 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010141 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010142 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010143 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010144 NewLHS = PHINode::Create(LHSType,
10145 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010146 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10147 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010148 InsertNewInstBefore(NewLHS, PN);
10149 LHSVal = NewLHS;
10150 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010151
10152 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010153 NewRHS = PHINode::Create(RHSType,
10154 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010155 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10156 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010157 InsertNewInstBefore(NewRHS, PN);
10158 RHSVal = NewRHS;
10159 }
10160
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010161 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010162 if (NewLHS || NewRHS) {
10163 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10164 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10165 if (NewLHS) {
10166 Value *NewInLHS = InInst->getOperand(0);
10167 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10168 }
10169 if (NewRHS) {
10170 Value *NewInRHS = InInst->getOperand(1);
10171 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10172 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010173 }
10174 }
10175
Chris Lattner7da52b22006-11-01 04:51:18 +000010176 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010177 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010178 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10179 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10180 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010181}
10182
Chris Lattner05f18922008-12-01 02:34:36 +000010183Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10184 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10185
10186 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10187 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010188 // This is true if all GEP bases are allocas and if all indices into them are
10189 // constants.
10190 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010191
10192 // Scan to see if all operands are the same opcode, all have one use, and all
10193 // kill their operands (i.e. the operands have one use).
10194 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10195 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10196 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10197 GEP->getNumOperands() != FirstInst->getNumOperands())
10198 return 0;
10199
Chris Lattner36d3e322009-02-21 00:46:50 +000010200 // Keep track of whether or not all GEPs are of alloca pointers.
10201 if (AllBasePointersAreAllocas &&
10202 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10203 !GEP->hasAllConstantIndices()))
10204 AllBasePointersAreAllocas = false;
10205
Chris Lattner05f18922008-12-01 02:34:36 +000010206 // Compare the operand lists.
10207 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10208 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10209 continue;
10210
10211 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10212 // if one of the PHIs has a constant for the index. The index may be
10213 // substantially cheaper to compute for the constants, so making it a
10214 // variable index could pessimize the path. This also handles the case
10215 // for struct indices, which must always be constant.
10216 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10217 isa<ConstantInt>(GEP->getOperand(op)))
10218 return 0;
10219
10220 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10221 return 0;
10222 FixedOperands[op] = 0; // Needs a PHI.
10223 }
10224 }
10225
Chris Lattner36d3e322009-02-21 00:46:50 +000010226 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010227 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010228 // offset calculation, but all the predecessors will have to materialize the
10229 // stack address into a register anyway. We'd actually rather *clone* the
10230 // load up into the predecessors so that we have a load of a gep of an alloca,
10231 // which can usually all be folded into the load.
10232 if (AllBasePointersAreAllocas)
10233 return 0;
10234
Chris Lattner05f18922008-12-01 02:34:36 +000010235 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10236 // that is variable.
10237 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10238
10239 bool HasAnyPHIs = false;
10240 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10241 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10242 Value *FirstOp = FirstInst->getOperand(i);
10243 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10244 FirstOp->getName()+".pn");
10245 InsertNewInstBefore(NewPN, PN);
10246
10247 NewPN->reserveOperandSpace(e);
10248 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10249 OperandPhis[i] = NewPN;
10250 FixedOperands[i] = NewPN;
10251 HasAnyPHIs = true;
10252 }
10253
10254
10255 // Add all operands to the new PHIs.
10256 if (HasAnyPHIs) {
10257 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10258 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10259 BasicBlock *InBB = PN.getIncomingBlock(i);
10260
10261 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10262 if (PHINode *OpPhi = OperandPhis[op])
10263 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10264 }
10265 }
10266
10267 Value *Base = FixedOperands[0];
10268 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10269 FixedOperands.end());
10270}
10271
10272
Chris Lattner21550882009-02-23 05:56:17 +000010273/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10274/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010275/// obvious the value of the load is not changed from the point of the load to
10276/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010277///
10278/// Finally, it is safe, but not profitable, to sink a load targetting a
10279/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10280/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010281static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010282 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10283
10284 for (++BBI; BBI != E; ++BBI)
10285 if (BBI->mayWriteToMemory())
10286 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010287
10288 // Check for non-address taken alloca. If not address-taken already, it isn't
10289 // profitable to do this xform.
10290 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10291 bool isAddressTaken = false;
10292 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10293 UI != E; ++UI) {
10294 if (isa<LoadInst>(UI)) continue;
10295 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10296 // If storing TO the alloca, then the address isn't taken.
10297 if (SI->getOperand(1) == AI) continue;
10298 }
10299 isAddressTaken = true;
10300 break;
10301 }
10302
Chris Lattner36d3e322009-02-21 00:46:50 +000010303 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010304 return false;
10305 }
10306
Chris Lattner36d3e322009-02-21 00:46:50 +000010307 // If this load is a load from a GEP with a constant offset from an alloca,
10308 // then we don't want to sink it. In its present form, it will be
10309 // load [constant stack offset]. Sinking it will cause us to have to
10310 // materialize the stack addresses in each predecessor in a register only to
10311 // do a shared load from register in the successor.
10312 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10313 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10314 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10315 return false;
10316
Chris Lattner76c73142006-11-01 07:13:54 +000010317 return true;
10318}
10319
Chris Lattner9fe38862003-06-19 17:00:31 +000010320
Chris Lattnerbac32862004-11-14 19:13:23 +000010321// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10322// operator and they all are only used by the PHI, PHI together their
10323// inputs, and do the operation once, to the result of the PHI.
10324Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10325 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10326
10327 // Scan the instruction, looking for input operations that can be folded away.
10328 // If all input operands to the phi are the same instruction (e.g. a cast from
10329 // the same type or "+42") we can pull the operation through the PHI, reducing
10330 // code size and simplifying code.
10331 Constant *ConstantOp = 0;
10332 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010333 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010334 if (isa<CastInst>(FirstInst)) {
10335 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010336 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010337 // Can fold binop, compare or shift here if the RHS is a constant,
10338 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010339 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010340 if (ConstantOp == 0)
10341 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010342 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10343 isVolatile = LI->isVolatile();
10344 // We can't sink the load if the loaded value could be modified between the
10345 // load and the PHI.
10346 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010347 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010348 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010349
10350 // If the PHI is of volatile loads and the load block has multiple
10351 // successors, sinking it would remove a load of the volatile value from
10352 // the path through the other successor.
10353 if (isVolatile &&
10354 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10355 return 0;
10356
Chris Lattner9c080502006-11-01 07:43:41 +000010357 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010358 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010359 } else {
10360 return 0; // Cannot fold this operation.
10361 }
10362
10363 // Check to see if all arguments are the same operation.
10364 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10365 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10366 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010367 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010368 return 0;
10369 if (CastSrcTy) {
10370 if (I->getOperand(0)->getType() != CastSrcTy)
10371 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010372 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010373 // We can't sink the load if the loaded value could be modified between
10374 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010375 if (LI->isVolatile() != isVolatile ||
10376 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010377 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010378 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010379
Chris Lattner71042962008-07-08 17:18:32 +000010380 // If the PHI is of volatile loads and the load block has multiple
10381 // successors, sinking it would remove a load of the volatile value from
10382 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010383 if (isVolatile &&
10384 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10385 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010386
Chris Lattnerbac32862004-11-14 19:13:23 +000010387 } else if (I->getOperand(1) != ConstantOp) {
10388 return 0;
10389 }
10390 }
10391
10392 // Okay, they are all the same operation. Create a new PHI node of the
10393 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010394 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10395 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010396 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010397
10398 Value *InVal = FirstInst->getOperand(0);
10399 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010400
10401 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010402 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10403 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10404 if (NewInVal != InVal)
10405 InVal = 0;
10406 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10407 }
10408
10409 Value *PhiVal;
10410 if (InVal) {
10411 // The new PHI unions all of the same values together. This is really
10412 // common, so we handle it intelligently here for compile-time speed.
10413 PhiVal = InVal;
10414 delete NewPN;
10415 } else {
10416 InsertNewInstBefore(NewPN, PN);
10417 PhiVal = NewPN;
10418 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010419
Chris Lattnerbac32862004-11-14 19:13:23 +000010420 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010421 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010422 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010423 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010424 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010425 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010426 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010427 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010428 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10429
10430 // If this was a volatile load that we are merging, make sure to loop through
10431 // and mark all the input loads as non-volatile. If we don't do this, we will
10432 // insert a new volatile load and the old ones will not be deletable.
10433 if (isVolatile)
10434 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10435 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10436
10437 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010438}
Chris Lattnera1be5662002-05-02 17:06:02 +000010439
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010440/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10441/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010442static bool DeadPHICycle(PHINode *PN,
10443 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010444 if (PN->use_empty()) return true;
10445 if (!PN->hasOneUse()) return false;
10446
10447 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010448 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010449 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010450
10451 // Don't scan crazily complex things.
10452 if (PotentiallyDeadPHIs.size() == 16)
10453 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010454
10455 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10456 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010457
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010458 return false;
10459}
10460
Chris Lattnercf5008a2007-11-06 21:52:06 +000010461/// PHIsEqualValue - Return true if this phi node is always equal to
10462/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10463/// z = some value; x = phi (y, z); y = phi (x, z)
10464static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10465 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10466 // See if we already saw this PHI node.
10467 if (!ValueEqualPHIs.insert(PN))
10468 return true;
10469
10470 // Don't scan crazily complex things.
10471 if (ValueEqualPHIs.size() == 16)
10472 return false;
10473
10474 // Scan the operands to see if they are either phi nodes or are equal to
10475 // the value.
10476 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10477 Value *Op = PN->getIncomingValue(i);
10478 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10479 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10480 return false;
10481 } else if (Op != NonPhiInVal)
10482 return false;
10483 }
10484
10485 return true;
10486}
10487
10488
Chris Lattner473945d2002-05-06 18:06:38 +000010489// PHINode simplification
10490//
Chris Lattner7e708292002-06-25 16:13:24 +000010491Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010492 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010493 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010494
Owen Anderson7e057142006-07-10 22:03:18 +000010495 if (Value *V = PN.hasConstantValue())
10496 return ReplaceInstUsesWith(PN, V);
10497
Owen Anderson7e057142006-07-10 22:03:18 +000010498 // If all PHI operands are the same operation, pull them through the PHI,
10499 // reducing code size.
10500 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010501 isa<Instruction>(PN.getIncomingValue(1)) &&
10502 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10503 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10504 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10505 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010506 PN.getIncomingValue(0)->hasOneUse())
10507 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10508 return Result;
10509
10510 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10511 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10512 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010513 if (PN.hasOneUse()) {
10514 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10515 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010516 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010517 PotentiallyDeadPHIs.insert(&PN);
10518 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10519 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10520 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010521
10522 // If this phi has a single use, and if that use just computes a value for
10523 // the next iteration of a loop, delete the phi. This occurs with unused
10524 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10525 // common case here is good because the only other things that catch this
10526 // are induction variable analysis (sometimes) and ADCE, which is only run
10527 // late.
10528 if (PHIUser->hasOneUse() &&
10529 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10530 PHIUser->use_back() == &PN) {
10531 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10532 }
10533 }
Owen Anderson7e057142006-07-10 22:03:18 +000010534
Chris Lattnercf5008a2007-11-06 21:52:06 +000010535 // We sometimes end up with phi cycles that non-obviously end up being the
10536 // same value, for example:
10537 // z = some value; x = phi (y, z); y = phi (x, z)
10538 // where the phi nodes don't necessarily need to be in the same block. Do a
10539 // quick check to see if the PHI node only contains a single non-phi value, if
10540 // so, scan to see if the phi cycle is actually equal to that value.
10541 {
10542 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10543 // Scan for the first non-phi operand.
10544 while (InValNo != NumOperandVals &&
10545 isa<PHINode>(PN.getIncomingValue(InValNo)))
10546 ++InValNo;
10547
10548 if (InValNo != NumOperandVals) {
10549 Value *NonPhiInVal = PN.getOperand(InValNo);
10550
10551 // Scan the rest of the operands to see if there are any conflicts, if so
10552 // there is no need to recursively scan other phis.
10553 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10554 Value *OpVal = PN.getIncomingValue(InValNo);
10555 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10556 break;
10557 }
10558
10559 // If we scanned over all operands, then we have one unique value plus
10560 // phi values. Scan PHI nodes to see if they all merge in each other or
10561 // the value.
10562 if (InValNo == NumOperandVals) {
10563 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10564 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10565 return ReplaceInstUsesWith(PN, NonPhiInVal);
10566 }
10567 }
10568 }
Chris Lattner60921c92003-12-19 05:58:40 +000010569 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010570}
10571
Reid Spencer17212df2006-12-12 09:18:51 +000010572static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10573 Instruction *InsertPoint,
10574 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010575 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10576 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010577 // We must cast correctly to the pointer type. Ensure that we
10578 // sign extend the integer value if it is smaller as this is
10579 // used for address computation.
10580 Instruction::CastOps opcode =
10581 (VTySize < PtrSize ? Instruction::SExt :
10582 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10583 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010584}
10585
Chris Lattnera1be5662002-05-02 17:06:02 +000010586
Chris Lattner7e708292002-06-25 16:13:24 +000010587Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010588 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010589 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010590 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010591 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010592 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010593
Chris Lattnere87597f2004-10-16 18:11:37 +000010594 if (isa<UndefValue>(GEP.getOperand(0)))
10595 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10596
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010597 bool HasZeroPointerIndex = false;
10598 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10599 HasZeroPointerIndex = C->isNullValue();
10600
10601 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010602 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010603
Chris Lattner28977af2004-04-05 01:30:19 +000010604 // Eliminate unneeded casts for indices.
10605 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010606
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010607 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010608 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10609 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010610 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010611 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010612 if (CI->getOpcode() == Instruction::ZExt ||
10613 CI->getOpcode() == Instruction::SExt) {
10614 const Type *SrcTy = CI->getOperand(0)->getType();
10615 // We can eliminate a cast from i32 to i64 iff the target
10616 // is a 32-bit pointer target.
10617 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10618 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010619 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010620 }
10621 }
10622 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010623 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010624 // to what we need. If narrower, sign-extend it to what we need.
10625 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010626 // insert it. This explicit cast can make subsequent optimizations more
10627 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010628 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010629 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010630 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010631 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010632 MadeChange = true;
10633 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010634 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10635 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010636 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010637 MadeChange = true;
10638 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010639 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10640 if (Constant *C = dyn_cast<Constant>(Op)) {
10641 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10642 MadeChange = true;
10643 } else {
10644 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10645 GEP);
10646 *i = Op;
10647 MadeChange = true;
10648 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010649 }
Chris Lattner28977af2004-04-05 01:30:19 +000010650 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010651 }
Chris Lattner28977af2004-04-05 01:30:19 +000010652 if (MadeChange) return &GEP;
10653
Chris Lattner90ac28c2002-08-02 19:29:35 +000010654 // Combine Indices - If the source pointer to this getelementptr instruction
10655 // is a getelementptr instruction, combine the indices of the two
10656 // getelementptr instructions into a single instruction.
10657 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010658 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010659 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010660 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010661
10662 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010663 // Note that if our source is a gep chain itself that we wait for that
10664 // chain to be resolved before we perform this transformation. This
10665 // avoids us creating a TON of code in some cases.
10666 //
10667 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10668 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10669 return 0; // Wait until our source is folded to completion.
10670
Chris Lattner72588fc2007-02-15 22:48:32 +000010671 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010672
10673 // Find out whether the last index in the source GEP is a sequential idx.
10674 bool EndsWithSequential = false;
10675 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10676 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010677 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010678
Chris Lattner90ac28c2002-08-02 19:29:35 +000010679 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010680 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010681 // Replace: gep (gep %P, long B), long A, ...
10682 // With: T = long A+B; gep %P, T, ...
10683 //
Chris Lattner620ce142004-05-07 22:09:22 +000010684 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010685 if (SO1 == Constant::getNullValue(SO1->getType())) {
10686 Sum = GO1;
10687 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10688 Sum = SO1;
10689 } else {
10690 // If they aren't the same type, convert both to an integer of the
10691 // target's pointer size.
10692 if (SO1->getType() != GO1->getType()) {
10693 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010694 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010695 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010696 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010697 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010698 unsigned PS = TD->getPointerSizeInBits();
10699 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010700 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010701 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010702
Duncan Sands514ab342007-11-01 20:53:16 +000010703 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010704 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010705 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010706 } else {
10707 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010708 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10709 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010710 }
10711 }
10712 }
Chris Lattner620ce142004-05-07 22:09:22 +000010713 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10714 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10715 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010716 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010717 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010718 }
Chris Lattner28977af2004-04-05 01:30:19 +000010719 }
Chris Lattner620ce142004-05-07 22:09:22 +000010720
10721 // Recycle the GEP we already have if possible.
10722 if (SrcGEPOperands.size() == 2) {
10723 GEP.setOperand(0, SrcGEPOperands[0]);
10724 GEP.setOperand(1, Sum);
10725 return &GEP;
10726 } else {
10727 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10728 SrcGEPOperands.end()-1);
10729 Indices.push_back(Sum);
10730 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10731 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010732 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010733 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010734 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010735 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010736 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10737 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010738 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10739 }
10740
10741 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010742 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10743 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010744
Chris Lattner620ce142004-05-07 22:09:22 +000010745 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010746 // GEP of global variable. If all of the indices for this GEP are
10747 // constants, we can promote this to a constexpr instead of an instruction.
10748
10749 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010750 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010751 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10752 for (; I != E && isa<Constant>(*I); ++I)
10753 Indices.push_back(cast<Constant>(*I));
10754
10755 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010756 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10757 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010758
10759 // Replace all uses of the GEP with the new constexpr...
10760 return ReplaceInstUsesWith(GEP, CE);
10761 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010762 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010763 if (!isa<PointerType>(X->getType())) {
10764 // Not interesting. Source pointer must be a cast from pointer.
10765 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010766 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10767 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010768 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010769 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10770 // into : GEP i8* X, ...
10771 //
Chris Lattnereed48272005-09-13 00:40:14 +000010772 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010773 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10774 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010775 if (const ArrayType *CATy =
10776 dyn_cast<ArrayType>(CPTy->getElementType())) {
10777 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10778 if (CATy->getElementType() == XTy->getElementType()) {
10779 // -> GEP i8* X, ...
10780 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10781 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10782 GEP.getName());
10783 } else if (const ArrayType *XATy =
10784 dyn_cast<ArrayType>(XTy->getElementType())) {
10785 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010786 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010787 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010788 // At this point, we know that the cast source type is a pointer
10789 // to an array of the same type as the destination pointer
10790 // array. Because the array type is never stepped over (there
10791 // is a leading zero) we can fold the cast into this GEP.
10792 GEP.setOperand(0, X);
10793 return &GEP;
10794 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010795 }
10796 }
Chris Lattnereed48272005-09-13 00:40:14 +000010797 } else if (GEP.getNumOperands() == 2) {
10798 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010799 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10800 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010801 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10802 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10803 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010804 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10805 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010806 Value *Idx[2];
10807 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10808 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010809 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010810 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010811 // V and GEP are both pointer types --> BitCast
10812 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010813 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010814
10815 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010816 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010817 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010818 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010819
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010820 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010821 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010822 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010823
10824 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10825 // allow either a mul, shift, or constant here.
10826 Value *NewIdx = 0;
10827 ConstantInt *Scale = 0;
10828 if (ArrayEltSize == 1) {
10829 NewIdx = GEP.getOperand(1);
10830 Scale = ConstantInt::get(NewIdx->getType(), 1);
10831 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010832 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010833 Scale = CI;
10834 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10835 if (Inst->getOpcode() == Instruction::Shl &&
10836 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010837 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10838 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10839 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010840 NewIdx = Inst->getOperand(0);
10841 } else if (Inst->getOpcode() == Instruction::Mul &&
10842 isa<ConstantInt>(Inst->getOperand(1))) {
10843 Scale = cast<ConstantInt>(Inst->getOperand(1));
10844 NewIdx = Inst->getOperand(0);
10845 }
10846 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010847
Chris Lattner7835cdd2005-09-13 18:36:04 +000010848 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010849 // out, perform the transformation. Note, we don't know whether Scale is
10850 // signed or not. We'll use unsigned version of division/modulo
10851 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000010852 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010853 Scale->getZExtValue() % ArrayEltSize == 0) {
10854 Scale = ConstantInt::get(Scale->getType(),
10855 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010856 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010857 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010858 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010859 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010860 NewIdx = InsertNewInstBefore(Sc, GEP);
10861 }
10862
10863 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010864 Value *Idx[2];
10865 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10866 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010867 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010868 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010869 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10870 // The NewGEP must be pointer typed, so must the old one -> BitCast
10871 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010872 }
10873 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010874 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010875 }
Chris Lattner58407792009-01-09 04:53:57 +000010876
Chris Lattner46cd5a12009-01-09 05:44:56 +000010877 /// See if we can simplify:
10878 /// X = bitcast A to B*
10879 /// Y = gep X, <...constant indices...>
10880 /// into a gep of the original struct. This is important for SROA and alias
10881 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010882 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010883 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10884 // Determine how much the GEP moves the pointer. We are guaranteed to get
10885 // a constant back from EmitGEPOffset.
10886 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10887 int64_t Offset = OffsetV->getSExtValue();
10888
10889 // If this GEP instruction doesn't move the pointer, just replace the GEP
10890 // with a bitcast of the real input to the dest type.
10891 if (Offset == 0) {
10892 // If the bitcast is of an allocation, and the allocation will be
10893 // converted to match the type of the cast, don't touch this.
10894 if (isa<AllocationInst>(BCI->getOperand(0))) {
10895 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10896 if (Instruction *I = visitBitCast(*BCI)) {
10897 if (I != BCI) {
10898 I->takeName(BCI);
10899 BCI->getParent()->getInstList().insert(BCI, I);
10900 ReplaceInstUsesWith(*BCI, I);
10901 }
10902 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010903 }
Chris Lattner58407792009-01-09 04:53:57 +000010904 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010905 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010906 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010907
10908 // Otherwise, if the offset is non-zero, we need to find out if there is a
10909 // field at Offset in 'A's type. If so, we can pull the cast through the
10910 // GEP.
10911 SmallVector<Value*, 8> NewIndices;
10912 const Type *InTy =
10913 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10914 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10915 Instruction *NGEP =
10916 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10917 NewIndices.end());
10918 if (NGEP->getType() == GEP.getType()) return NGEP;
10919 InsertNewInstBefore(NGEP, GEP);
10920 NGEP->takeName(&GEP);
10921 return new BitCastInst(NGEP, GEP.getType());
10922 }
Chris Lattner58407792009-01-09 04:53:57 +000010923 }
10924 }
10925
Chris Lattner8a2a3112001-12-14 16:52:21 +000010926 return 0;
10927}
10928
Chris Lattner0864acf2002-11-04 16:18:53 +000010929Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10930 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010931 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010932 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10933 const Type *NewTy =
10934 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010935 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010936
10937 // Create and insert the replacement instruction...
10938 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010939 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010940 else {
10941 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010942 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010943 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010944
10945 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010946
Chris Lattner0864acf2002-11-04 16:18:53 +000010947 // Scan to the end of the allocation instructions, to skip over a block of
10948 // allocas if possible...
10949 //
10950 BasicBlock::iterator It = New;
10951 while (isa<AllocationInst>(*It)) ++It;
10952
10953 // Now that I is pointing to the first non-allocation-inst in the block,
10954 // insert our getelementptr instruction...
10955 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010956 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010957 Value *Idx[2];
10958 Idx[0] = NullIdx;
10959 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010960 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10961 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010962
10963 // Now make everything use the getelementptr instead of the original
10964 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010965 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010966 } else if (isa<UndefValue>(AI.getArraySize())) {
10967 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010968 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010969 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010970
Dan Gohman6893cd72009-01-13 20:18:38 +000010971 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10972 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10973 // Note that we only do this for alloca's, because malloc should allocate and
10974 // return a unique pointer, even for a zero byte allocation.
10975 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10976 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10977
10978 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10979 if (AI.getAlignment() == 0)
10980 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10981 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010982
Chris Lattner0864acf2002-11-04 16:18:53 +000010983 return 0;
10984}
10985
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010986Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10987 Value *Op = FI.getOperand(0);
10988
Chris Lattner17be6352004-10-18 02:59:09 +000010989 // free undef -> unreachable.
10990 if (isa<UndefValue>(Op)) {
10991 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010992 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010993 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010994 return EraseInstFromFunction(FI);
10995 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010996
Chris Lattner6160e852004-02-28 04:57:37 +000010997 // If we have 'free null' delete the instruction. This can happen in stl code
10998 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010999 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011000 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011001
11002 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11003 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11004 FI.setOperand(0, CI->getOperand(0));
11005 return &FI;
11006 }
11007
11008 // Change free (gep X, 0,0,0,0) into free(X)
11009 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11010 if (GEPI->hasAllZeroIndices()) {
11011 AddToWorkList(GEPI);
11012 FI.setOperand(0, GEPI->getOperand(0));
11013 return &FI;
11014 }
11015 }
11016
11017 // Change free(malloc) into nothing, if the malloc has a single use.
11018 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11019 if (MI->hasOneUse()) {
11020 EraseInstFromFunction(FI);
11021 return EraseInstFromFunction(*MI);
11022 }
Chris Lattner6160e852004-02-28 04:57:37 +000011023
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011024 return 0;
11025}
11026
11027
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011028/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011029static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011030 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011031 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011032 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011033
Devang Patel99db6ad2007-10-18 19:52:32 +000011034 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11035 // Instead of loading constant c string, use corresponding integer value
11036 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000011037 std::string Str;
11038 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011039 unsigned len = Str.length();
11040 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11041 unsigned numBits = Ty->getPrimitiveSizeInBits();
11042 // Replace LI with immediate integer store.
11043 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000011044 APInt StrVal(numBits, 0);
11045 APInt SingleChar(numBits, 0);
11046 if (TD->isLittleEndian()) {
11047 for (signed i = len-1; i >= 0; i--) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011048 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011049 StrVal = (StrVal << 8) | SingleChar;
11050 }
11051 } else {
11052 for (unsigned i = 0; i < len; i++) {
Nick Lewycky2ec0dbf2009-02-21 20:50:42 +000011053 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling587c01d2008-02-26 10:53:30 +000011054 StrVal = (StrVal << 8) | SingleChar;
11055 }
11056 // Append NULL at the end.
11057 SingleChar = 0;
11058 StrVal = (StrVal << 8) | SingleChar;
11059 }
11060 Value *NL = ConstantInt::get(StrVal);
11061 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000011062 }
11063 }
11064 }
11065
Mon P Wang6753f952009-02-07 22:19:29 +000011066 const PointerType *DestTy = cast<PointerType>(CI->getType());
11067 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011068 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011069
11070 // If the address spaces don't match, don't eliminate the cast.
11071 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11072 return 0;
11073
Chris Lattnerb89e0712004-07-13 01:49:43 +000011074 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011075
Reid Spencer42230162007-01-22 05:51:25 +000011076 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011077 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011078 // If the source is an array, the code below will not succeed. Check to
11079 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11080 // constants.
11081 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11082 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11083 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011084 Value *Idxs[2];
11085 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11086 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011087 SrcTy = cast<PointerType>(CastOp->getType());
11088 SrcPTy = SrcTy->getElementType();
11089 }
11090
Reid Spencer42230162007-01-22 05:51:25 +000011091 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011092 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011093 // Do not allow turning this into a load of an integer, which is then
11094 // casted to a pointer, this pessimizes pointer analysis a lot.
11095 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011096 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11097 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011098
Chris Lattnerf9527852005-01-31 04:50:46 +000011099 // Okay, we are casting from one integer or pointer type to another of
11100 // the same size. Instead of casting the pointer before the load, cast
11101 // the result of the loaded value.
11102 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11103 CI->getName(),
11104 LI.isVolatile()),LI);
11105 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011106 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011107 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011108 }
11109 }
11110 return 0;
11111}
11112
Chris Lattnerc10aced2004-09-19 18:43:46 +000011113/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011114/// from this value cannot trap. If it is not obviously safe to load from the
11115/// specified pointer, we do a quick local scan of the basic block containing
11116/// ScanFrom, to determine if the address is already accessed.
11117static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011118 // If it is an alloca it is always safe to load from.
11119 if (isa<AllocaInst>(V)) return true;
11120
Duncan Sands46318cd2007-09-19 10:25:38 +000011121 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011122 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011123 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011124 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011125
11126 // Otherwise, be a little bit agressive by scanning the local block where we
11127 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011128 // from/to. If so, the previous load or store would have already trapped,
11129 // so there is no harm doing an extra load (also, CSE will later eliminate
11130 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011131 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11132
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011133 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011134 --BBI;
11135
Chris Lattner2de3fec2008-06-20 05:12:56 +000011136 // If we see a free or a call (which might do a free) the pointer could be
11137 // marked invalid.
11138 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11139 return false;
11140
Chris Lattner8a375202004-09-19 19:18:10 +000011141 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11142 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011143 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011144 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011145 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011146
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011147 }
Chris Lattner8a375202004-09-19 19:18:10 +000011148 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011149}
11150
Chris Lattner833b8a42003-06-26 05:06:25 +000011151Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11152 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011153
Dan Gohman9941f742007-07-20 16:34:21 +000011154 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011155 unsigned KnownAlign =
11156 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011157 if (KnownAlign >
11158 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11159 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011160 LI.setAlignment(KnownAlign);
11161
Chris Lattner37366c12005-05-01 04:24:53 +000011162 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011163 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011164 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011165 return Res;
11166
11167 // None of the following transforms are legal for volatile loads.
11168 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011169
Dan Gohman2276a7b2008-10-15 23:19:35 +000011170 // Do really simple store-to-load forwarding and load CSE, to catch cases
11171 // where there are several consequtive memory accesses to the same location,
11172 // separated by a few arithmetic operations.
11173 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011174 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11175 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011176
Christopher Lambb15147e2007-12-29 07:56:53 +000011177 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11178 const Value *GEPI0 = GEPI->getOperand(0);
11179 // TODO: Consider a target hook for valid address spaces for this xform.
11180 if (isa<ConstantPointerNull>(GEPI0) &&
11181 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011182 // Insert a new store to null instruction before the load to indicate
11183 // that this code is not reachable. We do this instead of inserting
11184 // an unreachable instruction directly because we cannot modify the
11185 // CFG.
11186 new StoreInst(UndefValue::get(LI.getType()),
11187 Constant::getNullValue(Op->getType()), &LI);
11188 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11189 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011190 }
Chris Lattner37366c12005-05-01 04:24:53 +000011191
Chris Lattnere87597f2004-10-16 18:11:37 +000011192 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011193 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011194 // TODO: Consider a target hook for valid address spaces for this xform.
11195 if (isa<UndefValue>(C) || (C->isNullValue() &&
11196 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011197 // Insert a new store to null instruction before the load to indicate that
11198 // this code is not reachable. We do this instead of inserting an
11199 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011200 new StoreInst(UndefValue::get(LI.getType()),
11201 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011202 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011203 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011204
Chris Lattnere87597f2004-10-16 18:11:37 +000011205 // Instcombine load (constant global) into the value loaded.
11206 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011207 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011208 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011209
Chris Lattnere87597f2004-10-16 18:11:37 +000011210 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011211 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011212 if (CE->getOpcode() == Instruction::GetElementPtr) {
11213 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011214 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011215 if (Constant *V =
11216 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011217 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011218 if (CE->getOperand(0)->isNullValue()) {
11219 // Insert a new store to null instruction before the load to indicate
11220 // that this code is not reachable. We do this instead of inserting
11221 // an unreachable instruction directly because we cannot modify the
11222 // CFG.
11223 new StoreInst(UndefValue::get(LI.getType()),
11224 Constant::getNullValue(Op->getType()), &LI);
11225 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11226 }
11227
Reid Spencer3da59db2006-11-27 01:05:10 +000011228 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011229 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011230 return Res;
11231 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011232 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011233 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011234
11235 // If this load comes from anywhere in a constant global, and if the global
11236 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011237 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011238 if (GV->isConstant() && GV->hasInitializer()) {
11239 if (GV->getInitializer()->isNullValue())
11240 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11241 else if (isa<UndefValue>(GV->getInitializer()))
11242 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11243 }
11244 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011245
Chris Lattner37366c12005-05-01 04:24:53 +000011246 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011247 // Change select and PHI nodes to select values instead of addresses: this
11248 // helps alias analysis out a lot, allows many others simplifications, and
11249 // exposes redundancy in the code.
11250 //
11251 // Note that we cannot do the transformation unless we know that the
11252 // introduced loads cannot trap! Something like this is valid as long as
11253 // the condition is always false: load (select bool %C, int* null, int* %G),
11254 // but it would not be valid if we transformed it to load from null
11255 // unconditionally.
11256 //
11257 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11258 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011259 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11260 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011261 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011262 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011263 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011264 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011265 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011266 }
11267
Chris Lattner684fe212004-09-23 15:46:00 +000011268 // load (select (cond, null, P)) -> load P
11269 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11270 if (C->isNullValue()) {
11271 LI.setOperand(0, SI->getOperand(2));
11272 return &LI;
11273 }
11274
11275 // load (select (cond, P, null)) -> load P
11276 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11277 if (C->isNullValue()) {
11278 LI.setOperand(0, SI->getOperand(1));
11279 return &LI;
11280 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011281 }
11282 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011283 return 0;
11284}
11285
Reid Spencer55af2b52007-01-19 21:20:31 +000011286/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011287/// when possible. This makes it generally easy to do alias analysis and/or
11288/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011289static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11290 User *CI = cast<User>(SI.getOperand(1));
11291 Value *CastOp = CI->getOperand(0);
11292
11293 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011294 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11295 if (SrcTy == 0) return 0;
11296
11297 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011298
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011299 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11300 return 0;
11301
Chris Lattner3914f722009-01-24 01:00:13 +000011302 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11303 /// to its first element. This allows us to handle things like:
11304 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11305 /// on 32-bit hosts.
11306 SmallVector<Value*, 4> NewGEPIndices;
11307
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011308 // If the source is an array, the code below will not succeed. Check to
11309 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11310 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011311 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11312 // Index through pointer.
11313 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11314 NewGEPIndices.push_back(Zero);
11315
11316 while (1) {
11317 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011318 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011319 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011320 NewGEPIndices.push_back(Zero);
11321 SrcPTy = STy->getElementType(0);
11322 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11323 NewGEPIndices.push_back(Zero);
11324 SrcPTy = ATy->getElementType();
11325 } else {
11326 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011327 }
Chris Lattner3914f722009-01-24 01:00:13 +000011328 }
11329
11330 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11331 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011332
11333 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11334 return 0;
11335
Chris Lattner71759c42009-01-16 20:12:52 +000011336 // If the pointers point into different address spaces or if they point to
11337 // values with different sizes, we can't do the transformation.
11338 if (SrcTy->getAddressSpace() !=
11339 cast<PointerType>(CI->getType())->getAddressSpace() ||
11340 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011341 IC.getTargetData().getTypeSizeInBits(DestPTy))
11342 return 0;
11343
11344 // Okay, we are casting from one integer or pointer type to another of
11345 // the same size. Instead of casting the pointer before
11346 // the store, cast the value to be stored.
11347 Value *NewCast;
11348 Value *SIOp0 = SI.getOperand(0);
11349 Instruction::CastOps opcode = Instruction::BitCast;
11350 const Type* CastSrcTy = SIOp0->getType();
11351 const Type* CastDstTy = SrcPTy;
11352 if (isa<PointerType>(CastDstTy)) {
11353 if (CastSrcTy->isInteger())
11354 opcode = Instruction::IntToPtr;
11355 } else if (isa<IntegerType>(CastDstTy)) {
11356 if (isa<PointerType>(SIOp0->getType()))
11357 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011358 }
Chris Lattner3914f722009-01-24 01:00:13 +000011359
11360 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11361 // emit a GEP to index into its first field.
11362 if (!NewGEPIndices.empty()) {
11363 if (Constant *C = dyn_cast<Constant>(CastOp))
11364 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11365 NewGEPIndices.size());
11366 else
11367 CastOp = IC.InsertNewInstBefore(
11368 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11369 NewGEPIndices.end()), SI);
11370 }
11371
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011372 if (Constant *C = dyn_cast<Constant>(SIOp0))
11373 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11374 else
11375 NewCast = IC.InsertNewInstBefore(
11376 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11377 SI);
11378 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011379}
11380
Chris Lattner4aebaee2008-11-27 08:56:30 +000011381/// equivalentAddressValues - Test if A and B will obviously have the same
11382/// value. This includes recognizing that %t0 and %t1 will have the same
11383/// value in code like this:
11384/// %t0 = getelementptr @a, 0, 3
11385/// store i32 0, i32* %t0
11386/// %t1 = getelementptr @a, 0, 3
11387/// %t2 = load i32* %t1
11388///
11389static bool equivalentAddressValues(Value *A, Value *B) {
11390 // Test if the values are trivially equivalent.
11391 if (A == B) return true;
11392
11393 // Test if the values come form identical arithmetic instructions.
11394 if (isa<BinaryOperator>(A) ||
11395 isa<CastInst>(A) ||
11396 isa<PHINode>(A) ||
11397 isa<GetElementPtrInst>(A))
11398 if (Instruction *BI = dyn_cast<Instruction>(B))
11399 if (cast<Instruction>(A)->isIdenticalTo(BI))
11400 return true;
11401
11402 // Otherwise they may not be equivalent.
11403 return false;
11404}
11405
Chris Lattner2f503e62005-01-31 05:36:43 +000011406Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11407 Value *Val = SI.getOperand(0);
11408 Value *Ptr = SI.getOperand(1);
11409
11410 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011411 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011412 ++NumCombined;
11413 return 0;
11414 }
Chris Lattner836692d2007-01-15 06:51:56 +000011415
11416 // If the RHS is an alloca with a single use, zapify the store, making the
11417 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011418 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011419 if (isa<AllocaInst>(Ptr)) {
11420 EraseInstFromFunction(SI);
11421 ++NumCombined;
11422 return 0;
11423 }
11424
11425 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11426 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11427 GEP->getOperand(0)->hasOneUse()) {
11428 EraseInstFromFunction(SI);
11429 ++NumCombined;
11430 return 0;
11431 }
11432 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011433
Dan Gohman9941f742007-07-20 16:34:21 +000011434 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011435 unsigned KnownAlign =
11436 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011437 if (KnownAlign >
11438 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11439 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011440 SI.setAlignment(KnownAlign);
11441
Dale Johannesenacb51a32009-03-03 01:43:03 +000011442 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011443 // stores to the same location, separated by a few arithmetic operations. This
11444 // situation often occurs with bitfield accesses.
11445 BasicBlock::iterator BBI = &SI;
11446 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11447 --ScanInsts) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011448 // Don't count debug info directives, lest they affect codegen.
11449 if (isa<DbgInfoIntrinsic>(BBI)) {
11450 ScanInsts++;
11451 --BBI;
11452 continue;
11453 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011454 --BBI;
11455
11456 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11457 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011458 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11459 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011460 ++NumDeadStore;
11461 ++BBI;
11462 EraseInstFromFunction(*PrevSI);
11463 continue;
11464 }
11465 break;
11466 }
11467
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011468 // If this is a load, we have to stop. However, if the loaded value is from
11469 // the pointer we're loading and is producing the pointer we're storing,
11470 // then *this* store is dead (X = load P; store X -> P).
11471 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011472 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11473 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011474 EraseInstFromFunction(SI);
11475 ++NumCombined;
11476 return 0;
11477 }
11478 // Otherwise, this is a load from some other location. Stores before it
11479 // may not be dead.
11480 break;
11481 }
11482
Chris Lattner9ca96412006-02-08 03:25:32 +000011483 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011484 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011485 break;
11486 }
11487
11488
11489 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011490
11491 // store X, null -> turns into 'unreachable' in SimplifyCFG
11492 if (isa<ConstantPointerNull>(Ptr)) {
11493 if (!isa<UndefValue>(Val)) {
11494 SI.setOperand(0, UndefValue::get(Val->getType()));
11495 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011496 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011497 ++NumCombined;
11498 }
11499 return 0; // Do not modify these!
11500 }
11501
11502 // store undef, Ptr -> noop
11503 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011504 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011505 ++NumCombined;
11506 return 0;
11507 }
11508
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011509 // If the pointer destination is a cast, see if we can fold the cast into the
11510 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011511 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011512 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11513 return Res;
11514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011515 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011516 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11517 return Res;
11518
Chris Lattner408902b2005-09-12 23:23:25 +000011519
11520 // If this store is the last instruction in the basic block, and if the block
11521 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011522 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011523 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011524 if (BI->isUnconditional())
11525 if (SimplifyStoreAtEndOfBlock(SI))
11526 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011527
Chris Lattner2f503e62005-01-31 05:36:43 +000011528 return 0;
11529}
11530
Chris Lattner3284d1f2007-04-15 00:07:55 +000011531/// SimplifyStoreAtEndOfBlock - Turn things like:
11532/// if () { *P = v1; } else { *P = v2 }
11533/// into a phi node with a store in the successor.
11534///
Chris Lattner31755a02007-04-15 01:02:18 +000011535/// Simplify things like:
11536/// *P = v1; if () { *P = v2; }
11537/// into a phi node with a store in the successor.
11538///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011539bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11540 BasicBlock *StoreBB = SI.getParent();
11541
11542 // Check to see if the successor block has exactly two incoming edges. If
11543 // so, see if the other predecessor contains a store to the same location.
11544 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011545 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011546
11547 // Determine whether Dest has exactly two predecessors and, if so, compute
11548 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011549 pred_iterator PI = pred_begin(DestBB);
11550 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011551 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011552 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011553 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011554 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011555 return false;
11556
11557 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011558 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011559 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011560 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011561 }
Chris Lattner31755a02007-04-15 01:02:18 +000011562 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011563 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011564
11565 // Bail out if all the relevant blocks aren't distinct (this can happen,
11566 // for example, if SI is in an infinite loop)
11567 if (StoreBB == DestBB || OtherBB == DestBB)
11568 return false;
11569
Chris Lattner31755a02007-04-15 01:02:18 +000011570 // Verify that the other block ends in a branch and is not otherwise empty.
11571 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011572 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011573 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011574 return false;
11575
Chris Lattner31755a02007-04-15 01:02:18 +000011576 // If the other block ends in an unconditional branch, check for the 'if then
11577 // else' case. there is an instruction before the branch.
11578 StoreInst *OtherStore = 0;
11579 if (OtherBr->isUnconditional()) {
11580 // If this isn't a store, or isn't a store to the same location, bail out.
11581 --BBI;
11582 OtherStore = dyn_cast<StoreInst>(BBI);
11583 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11584 return false;
11585 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011586 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011587 // destinations is StoreBB, then we have the if/then case.
11588 if (OtherBr->getSuccessor(0) != StoreBB &&
11589 OtherBr->getSuccessor(1) != StoreBB)
11590 return false;
11591
11592 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011593 // if/then triangle. See if there is a store to the same ptr as SI that
11594 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011595 for (;; --BBI) {
11596 // Check to see if we find the matching store.
11597 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11598 if (OtherStore->getOperand(1) != SI.getOperand(1))
11599 return false;
11600 break;
11601 }
Eli Friedman6903a242008-06-13 22:02:12 +000011602 // If we find something that may be using or overwriting the stored
11603 // value, or if we run out of instructions, we can't do the xform.
11604 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011605 BBI == OtherBB->begin())
11606 return false;
11607 }
11608
11609 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011610 // make sure nothing reads or overwrites the stored value in
11611 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011612 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11613 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011614 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011615 return false;
11616 }
11617 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011618
Chris Lattner31755a02007-04-15 01:02:18 +000011619 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011620 Value *MergedVal = OtherStore->getOperand(0);
11621 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011622 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011623 PN->reserveOperandSpace(2);
11624 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011625 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11626 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011627 }
11628
11629 // Advance to a place where it is safe to insert the new store and
11630 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011631 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011632 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11633 OtherStore->isVolatile()), *BBI);
11634
11635 // Nuke the old stores.
11636 EraseInstFromFunction(SI);
11637 EraseInstFromFunction(*OtherStore);
11638 ++NumCombined;
11639 return true;
11640}
11641
Chris Lattner2f503e62005-01-31 05:36:43 +000011642
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011643Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11644 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011645 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011646 BasicBlock *TrueDest;
11647 BasicBlock *FalseDest;
11648 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11649 !isa<Constant>(X)) {
11650 // Swap Destinations and condition...
11651 BI.setCondition(X);
11652 BI.setSuccessor(0, FalseDest);
11653 BI.setSuccessor(1, TrueDest);
11654 return &BI;
11655 }
11656
Reid Spencere4d87aa2006-12-23 06:05:41 +000011657 // Cannonicalize fcmp_one -> fcmp_oeq
11658 FCmpInst::Predicate FPred; Value *Y;
11659 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11660 TrueDest, FalseDest)))
11661 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11662 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11663 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011664 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011665 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11666 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011667 // Swap Destinations and condition...
11668 BI.setCondition(NewSCC);
11669 BI.setSuccessor(0, FalseDest);
11670 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011671 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011672 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011673 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011674 return &BI;
11675 }
11676
11677 // Cannonicalize icmp_ne -> icmp_eq
11678 ICmpInst::Predicate IPred;
11679 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11680 TrueDest, FalseDest)))
11681 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11682 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11683 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11684 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011685 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011686 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11687 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011688 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011689 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011690 BI.setSuccessor(0, FalseDest);
11691 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011692 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011693 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011694 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011695 return &BI;
11696 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011697
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011698 return 0;
11699}
Chris Lattner0864acf2002-11-04 16:18:53 +000011700
Chris Lattner46238a62004-07-03 00:26:11 +000011701Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11702 Value *Cond = SI.getCondition();
11703 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11704 if (I->getOpcode() == Instruction::Add)
11705 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11706 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11707 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011708 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011709 AddRHS));
11710 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011711 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011712 return &SI;
11713 }
11714 }
11715 return 0;
11716}
11717
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011718Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011719 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011720
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011721 if (!EV.hasIndices())
11722 return ReplaceInstUsesWith(EV, Agg);
11723
11724 if (Constant *C = dyn_cast<Constant>(Agg)) {
11725 if (isa<UndefValue>(C))
11726 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11727
11728 if (isa<ConstantAggregateZero>(C))
11729 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11730
11731 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11732 // Extract the element indexed by the first index out of the constant
11733 Value *V = C->getOperand(*EV.idx_begin());
11734 if (EV.getNumIndices() > 1)
11735 // Extract the remaining indices out of the constant indexed by the
11736 // first index
11737 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11738 else
11739 return ReplaceInstUsesWith(EV, V);
11740 }
11741 return 0; // Can't handle other constants
11742 }
11743 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11744 // We're extracting from an insertvalue instruction, compare the indices
11745 const unsigned *exti, *exte, *insi, *inse;
11746 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11747 exte = EV.idx_end(), inse = IV->idx_end();
11748 exti != exte && insi != inse;
11749 ++exti, ++insi) {
11750 if (*insi != *exti)
11751 // The insert and extract both reference distinctly different elements.
11752 // This means the extract is not influenced by the insert, and we can
11753 // replace the aggregate operand of the extract with the aggregate
11754 // operand of the insert. i.e., replace
11755 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11756 // %E = extractvalue { i32, { i32 } } %I, 0
11757 // with
11758 // %E = extractvalue { i32, { i32 } } %A, 0
11759 return ExtractValueInst::Create(IV->getAggregateOperand(),
11760 EV.idx_begin(), EV.idx_end());
11761 }
11762 if (exti == exte && insi == inse)
11763 // Both iterators are at the end: Index lists are identical. Replace
11764 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11765 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11766 // with "i32 42"
11767 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11768 if (exti == exte) {
11769 // The extract list is a prefix of the insert list. i.e. replace
11770 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11771 // %E = extractvalue { i32, { i32 } } %I, 1
11772 // with
11773 // %X = extractvalue { i32, { i32 } } %A, 1
11774 // %E = insertvalue { i32 } %X, i32 42, 0
11775 // by switching the order of the insert and extract (though the
11776 // insertvalue should be left in, since it may have other uses).
11777 Value *NewEV = InsertNewInstBefore(
11778 ExtractValueInst::Create(IV->getAggregateOperand(),
11779 EV.idx_begin(), EV.idx_end()),
11780 EV);
11781 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11782 insi, inse);
11783 }
11784 if (insi == inse)
11785 // The insert list is a prefix of the extract list
11786 // We can simply remove the common indices from the extract and make it
11787 // operate on the inserted value instead of the insertvalue result.
11788 // i.e., replace
11789 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11790 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11791 // with
11792 // %E extractvalue { i32 } { i32 42 }, 0
11793 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11794 exti, exte);
11795 }
11796 // Can't simplify extracts from other values. Note that nested extracts are
11797 // already simplified implicitely by the above (extract ( extract (insert) )
11798 // will be translated into extract ( insert ( extract ) ) first and then just
11799 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011800 return 0;
11801}
11802
Chris Lattner220b0cf2006-03-05 00:22:33 +000011803/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11804/// is to leave as a vector operation.
11805static bool CheapToScalarize(Value *V, bool isConstant) {
11806 if (isa<ConstantAggregateZero>(V))
11807 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011808 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011809 if (isConstant) return true;
11810 // If all elts are the same, we can extract.
11811 Constant *Op0 = C->getOperand(0);
11812 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11813 if (C->getOperand(i) != Op0)
11814 return false;
11815 return true;
11816 }
11817 Instruction *I = dyn_cast<Instruction>(V);
11818 if (!I) return false;
11819
11820 // Insert element gets simplified to the inserted element or is deleted if
11821 // this is constant idx extract element and its a constant idx insertelt.
11822 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11823 isa<ConstantInt>(I->getOperand(2)))
11824 return true;
11825 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11826 return true;
11827 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11828 if (BO->hasOneUse() &&
11829 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11830 CheapToScalarize(BO->getOperand(1), isConstant)))
11831 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011832 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11833 if (CI->hasOneUse() &&
11834 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11835 CheapToScalarize(CI->getOperand(1), isConstant)))
11836 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011837
11838 return false;
11839}
11840
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011841/// Read and decode a shufflevector mask.
11842///
11843/// It turns undef elements into values that are larger than the number of
11844/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011845static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11846 unsigned NElts = SVI->getType()->getNumElements();
11847 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11848 return std::vector<unsigned>(NElts, 0);
11849 if (isa<UndefValue>(SVI->getOperand(2)))
11850 return std::vector<unsigned>(NElts, 2*NElts);
11851
11852 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011853 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011854 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11855 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011856 Result.push_back(NElts*2); // undef -> 8
11857 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011858 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011859 return Result;
11860}
11861
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011862/// FindScalarElement - Given a vector and an element number, see if the scalar
11863/// value is already around as a register, for example if it were inserted then
11864/// extracted from the vector.
11865static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011866 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11867 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011868 unsigned Width = PTy->getNumElements();
11869 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011870 return UndefValue::get(PTy->getElementType());
11871
11872 if (isa<UndefValue>(V))
11873 return UndefValue::get(PTy->getElementType());
11874 else if (isa<ConstantAggregateZero>(V))
11875 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011876 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011877 return CP->getOperand(EltNo);
11878 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11879 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011880 if (!isa<ConstantInt>(III->getOperand(2)))
11881 return 0;
11882 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011883
11884 // If this is an insert to the element we are looking for, return the
11885 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011886 if (EltNo == IIElt)
11887 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011888
11889 // Otherwise, the insertelement doesn't modify the value, recurse on its
11890 // vector input.
11891 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011892 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011893 unsigned LHSWidth =
11894 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011895 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011896 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011897 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011898 else if (InEl < LHSWidth*2)
11899 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011900 else
11901 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011902 }
11903
11904 // Otherwise, we don't know.
11905 return 0;
11906}
11907
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011908Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011909 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011910 if (isa<UndefValue>(EI.getOperand(0)))
11911 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11912
Dan Gohman07a96762007-07-16 14:29:03 +000011913 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011914 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11915 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11916
Reid Spencer9d6565a2007-02-15 02:26:10 +000011917 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011918 // If vector val is constant with all elements the same, replace EI with
11919 // that element. When the elements are not identical, we cannot replace yet
11920 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011921 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011922 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011923 if (C->getOperand(i) != op0) {
11924 op0 = 0;
11925 break;
11926 }
11927 if (op0)
11928 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011929 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011930
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011931 // If extracting a specified index from the vector, see if we can recursively
11932 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011933 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011934 unsigned IndexVal = IdxC->getZExtValue();
11935 unsigned VectorWidth =
11936 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11937
11938 // If this is extracting an invalid index, turn this into undef, to avoid
11939 // crashing the code below.
11940 if (IndexVal >= VectorWidth)
11941 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11942
Chris Lattner867b99f2006-10-05 06:55:50 +000011943 // This instruction only demands the single element from the input vector.
11944 // If the input vector has a single use, simplify it based on this use
11945 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011946 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000011947 APInt UndefElts(VectorWidth, 0);
11948 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000011949 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000011950 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011951 EI.setOperand(0, V);
11952 return &EI;
11953 }
11954 }
11955
Reid Spencerb83eb642006-10-20 07:07:24 +000011956 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011957 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011958
11959 // If the this extractelement is directly using a bitcast from a vector of
11960 // the same number of elements, see if we can find the source element from
11961 // it. In this case, we will end up needing to bitcast the scalars.
11962 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11963 if (const VectorType *VT =
11964 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11965 if (VT->getNumElements() == VectorWidth)
11966 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11967 return new BitCastInst(Elt, EI.getType());
11968 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011969 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011970
Chris Lattner73fa49d2006-05-25 22:53:38 +000011971 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011972 if (I->hasOneUse()) {
11973 // Push extractelement into predecessor operation if legal and
11974 // profitable to do so
11975 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011976 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11977 if (CheapToScalarize(BO, isConstantElt)) {
11978 ExtractElementInst *newEI0 =
11979 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11980 EI.getName()+".lhs");
11981 ExtractElementInst *newEI1 =
11982 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11983 EI.getName()+".rhs");
11984 InsertNewInstBefore(newEI0, EI);
11985 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011986 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011987 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011988 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011989 unsigned AS =
11990 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011991 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11992 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011993 GetElementPtrInst *GEP =
11994 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011995 InsertNewInstBefore(GEP, EI);
11996 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011997 }
11998 }
11999 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12000 // Extracting the inserted element?
12001 if (IE->getOperand(2) == EI.getOperand(1))
12002 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12003 // If the inserted and extracted elements are constants, they must not
12004 // be the same value, extract from the pre-inserted value instead.
12005 if (isa<Constant>(IE->getOperand(2)) &&
12006 isa<Constant>(EI.getOperand(1))) {
12007 AddUsesToWorkList(EI);
12008 EI.setOperand(0, IE->getOperand(0));
12009 return &EI;
12010 }
12011 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12012 // If this is extracting an element from a shufflevector, figure out where
12013 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012014 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12015 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012016 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012017 unsigned LHSWidth =
12018 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12019
12020 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012021 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012022 else if (SrcIdx < LHSWidth*2) {
12023 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012024 Src = SVI->getOperand(1);
12025 } else {
12026 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012027 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012028 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012029 }
12030 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012031 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012032 return 0;
12033}
12034
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012035/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12036/// elements from either LHS or RHS, return the shuffle mask and true.
12037/// Otherwise, return false.
12038static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12039 std::vector<Constant*> &Mask) {
12040 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12041 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012042 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012043
12044 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012045 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012046 return true;
12047 } else if (V == LHS) {
12048 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012049 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012050 return true;
12051 } else if (V == RHS) {
12052 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012053 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012054 return true;
12055 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12056 // If this is an insert of an extract from some other vector, include it.
12057 Value *VecOp = IEI->getOperand(0);
12058 Value *ScalarOp = IEI->getOperand(1);
12059 Value *IdxOp = IEI->getOperand(2);
12060
Chris Lattnerd929f062006-04-27 21:14:21 +000012061 if (!isa<ConstantInt>(IdxOp))
12062 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012063 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012064
12065 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12066 // Okay, we can handle this if the vector we are insertinting into is
12067 // transitively ok.
12068 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12069 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012070 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012071 return true;
12072 }
12073 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12074 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012075 EI->getOperand(0)->getType() == V->getType()) {
12076 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012077 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012078
12079 // This must be extracting from either LHS or RHS.
12080 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12081 // Okay, we can handle this if the vector we are insertinting into is
12082 // transitively ok.
12083 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12084 // If so, update the mask to reflect the inserted value.
12085 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012086 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012087 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012088 } else {
12089 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012090 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012091 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012092
12093 }
12094 return true;
12095 }
12096 }
12097 }
12098 }
12099 }
12100 // TODO: Handle shufflevector here!
12101
12102 return false;
12103}
12104
12105/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12106/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12107/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012108static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012109 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012110 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012111 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012112 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012113 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012114
12115 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012116 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012117 return V;
12118 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012119 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012120 return V;
12121 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12122 // If this is an insert of an extract from some other vector, include it.
12123 Value *VecOp = IEI->getOperand(0);
12124 Value *ScalarOp = IEI->getOperand(1);
12125 Value *IdxOp = IEI->getOperand(2);
12126
12127 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12128 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12129 EI->getOperand(0)->getType() == V->getType()) {
12130 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012131 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12132 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012133
12134 // Either the extracted from or inserted into vector must be RHSVec,
12135 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012136 if (EI->getOperand(0) == RHS || RHS == 0) {
12137 RHS = EI->getOperand(0);
12138 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012139 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012140 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012141 return V;
12142 }
12143
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012144 if (VecOp == RHS) {
12145 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012146 // Everything but the extracted element is replaced with the RHS.
12147 for (unsigned i = 0; i != NumElts; ++i) {
12148 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012149 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012150 }
12151 return V;
12152 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012153
12154 // If this insertelement is a chain that comes from exactly these two
12155 // vectors, return the vector and the effective shuffle.
12156 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12157 return EI->getOperand(0);
12158
Chris Lattnerefb47352006-04-15 01:39:45 +000012159 }
12160 }
12161 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012162 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012163
12164 // Otherwise, can't do anything fancy. Return an identity vector.
12165 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012166 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012167 return V;
12168}
12169
12170Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12171 Value *VecOp = IE.getOperand(0);
12172 Value *ScalarOp = IE.getOperand(1);
12173 Value *IdxOp = IE.getOperand(2);
12174
Chris Lattner599ded12007-04-09 01:11:16 +000012175 // Inserting an undef or into an undefined place, remove this.
12176 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12177 ReplaceInstUsesWith(IE, VecOp);
12178
Chris Lattnerefb47352006-04-15 01:39:45 +000012179 // If the inserted element was extracted from some other vector, and if the
12180 // indexes are constant, try to turn this into a shufflevector operation.
12181 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12182 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12183 EI->getOperand(0)->getType() == IE.getType()) {
12184 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012185 unsigned ExtractedIdx =
12186 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012187 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012188
12189 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12190 return ReplaceInstUsesWith(IE, VecOp);
12191
12192 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12193 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12194
12195 // If we are extracting a value from a vector, then inserting it right
12196 // back into the same place, just use the input vector.
12197 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12198 return ReplaceInstUsesWith(IE, VecOp);
12199
12200 // We could theoretically do this for ANY input. However, doing so could
12201 // turn chains of insertelement instructions into a chain of shufflevector
12202 // instructions, and right now we do not merge shufflevectors. As such,
12203 // only do this in a situation where it is clear that there is benefit.
12204 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12205 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12206 // the values of VecOp, except then one read from EIOp0.
12207 // Build a new shuffle mask.
12208 std::vector<Constant*> Mask;
12209 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012210 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012211 else {
12212 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012213 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012214 NumVectorElts));
12215 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012216 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012217 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012218 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012219 }
12220
12221 // If this insertelement isn't used by some other insertelement, turn it
12222 // (and any insertelements it points to), into one big shuffle.
12223 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12224 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012225 Value *RHS = 0;
12226 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12227 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12228 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012229 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012230 }
12231 }
12232 }
12233
12234 return 0;
12235}
12236
12237
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012238Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12239 Value *LHS = SVI.getOperand(0);
12240 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012241 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012242
12243 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012244
Chris Lattner867b99f2006-10-05 06:55:50 +000012245 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012246 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012247 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012248
Dan Gohman488fbfc2008-09-09 18:11:14 +000012249 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012250
12251 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12252 return 0;
12253
Evan Cheng388df622009-02-03 10:05:09 +000012254 APInt UndefElts(VWidth, 0);
12255 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12256 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012257 LHS = SVI.getOperand(0);
12258 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012259 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012260 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012261
Chris Lattner863bcff2006-05-25 23:48:38 +000012262 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12263 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12264 if (LHS == RHS || isa<UndefValue>(LHS)) {
12265 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012266 // shuffle(undef,undef,mask) -> undef.
12267 return ReplaceInstUsesWith(SVI, LHS);
12268 }
12269
Chris Lattner863bcff2006-05-25 23:48:38 +000012270 // Remap any references to RHS to use LHS.
12271 std::vector<Constant*> Elts;
12272 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012273 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012274 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012275 else {
12276 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012277 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012278 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012279 Elts.push_back(UndefValue::get(Type::Int32Ty));
12280 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012281 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012282 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12283 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012284 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012285 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012286 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012287 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012288 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012289 LHS = SVI.getOperand(0);
12290 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012291 MadeChange = true;
12292 }
12293
Chris Lattner7b2e27922006-05-26 00:29:06 +000012294 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012295 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012296
Chris Lattner863bcff2006-05-25 23:48:38 +000012297 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12298 if (Mask[i] >= e*2) continue; // Ignore undef values.
12299 // Is this an identity shuffle of the LHS value?
12300 isLHSID &= (Mask[i] == i);
12301
12302 // Is this an identity shuffle of the RHS value?
12303 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012304 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012305
Chris Lattner863bcff2006-05-25 23:48:38 +000012306 // Eliminate identity shuffles.
12307 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12308 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012309
Chris Lattner7b2e27922006-05-26 00:29:06 +000012310 // If the LHS is a shufflevector itself, see if we can combine it with this
12311 // one without producing an unusual shuffle. Here we are really conservative:
12312 // we are absolutely afraid of producing a shuffle mask not in the input
12313 // program, because the code gen may not be smart enough to turn a merged
12314 // shuffle into two specific shuffles: it may produce worse code. As such,
12315 // we only merge two shuffles if the result is one of the two input shuffle
12316 // masks. In this case, merging the shuffles just removes one instruction,
12317 // which we know is safe. This is good for things like turning:
12318 // (splat(splat)) -> splat.
12319 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12320 if (isa<UndefValue>(RHS)) {
12321 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12322
12323 std::vector<unsigned> NewMask;
12324 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12325 if (Mask[i] >= 2*e)
12326 NewMask.push_back(2*e);
12327 else
12328 NewMask.push_back(LHSMask[Mask[i]]);
12329
12330 // If the result mask is equal to the src shuffle or this shuffle mask, do
12331 // the replacement.
12332 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012333 unsigned LHSInNElts =
12334 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012335 std::vector<Constant*> Elts;
12336 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012337 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012338 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012339 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012340 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012341 }
12342 }
12343 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12344 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012345 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012346 }
12347 }
12348 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012349
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012350 return MadeChange ? &SVI : 0;
12351}
12352
12353
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012354
Chris Lattnerea1c4542004-12-08 23:43:58 +000012355
12356/// TryToSinkInstruction - Try to move the specified instruction from its
12357/// current block into the beginning of DestBlock, which can only happen if it's
12358/// safe to move the instruction past all of the instructions between it and the
12359/// end of its block.
12360static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12361 assert(I->hasOneUse() && "Invariants didn't hold!");
12362
Chris Lattner108e9022005-10-27 17:13:11 +000012363 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012364 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12365 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012366
Chris Lattnerea1c4542004-12-08 23:43:58 +000012367 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012368 if (isa<AllocaInst>(I) && I->getParent() ==
12369 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012370 return false;
12371
Chris Lattner96a52a62004-12-09 07:14:34 +000012372 // We can only sink load instructions if there is nothing between the load and
12373 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012374 if (I->mayReadFromMemory()) {
12375 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012376 Scan != E; ++Scan)
12377 if (Scan->mayWriteToMemory())
12378 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012379 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012380
Dan Gohman02dea8b2008-05-23 21:05:58 +000012381 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012382
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012383 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012384 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012385 ++NumSunkInst;
12386 return true;
12387}
12388
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012389
12390/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12391/// all reachable code to the worklist.
12392///
12393/// This has a couple of tricks to make the code faster and more powerful. In
12394/// particular, we constant fold and DCE instructions as we go, to avoid adding
12395/// them to the worklist (this significantly speeds up instcombine on code where
12396/// many instructions are dead or constant). Additionally, if we find a branch
12397/// whose condition is a known constant, we only visit the reachable successors.
12398///
12399static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012400 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012401 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012402 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012403 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012404 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012405
Chris Lattner2c7718a2007-03-23 19:17:18 +000012406 while (!Worklist.empty()) {
12407 BB = Worklist.back();
12408 Worklist.pop_back();
12409
12410 // We have now visited this block! If we've already been here, ignore it.
12411 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012412
12413 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012414 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12415 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012416
Chris Lattner2c7718a2007-03-23 19:17:18 +000012417 // DCE instruction if trivially dead.
12418 if (isInstructionTriviallyDead(Inst)) {
12419 ++NumDeadInst;
12420 DOUT << "IC: DCE: " << *Inst;
12421 Inst->eraseFromParent();
12422 continue;
12423 }
12424
12425 // ConstantProp instruction if trivially constant.
12426 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12427 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12428 Inst->replaceAllUsesWith(C);
12429 ++NumConstProp;
12430 Inst->eraseFromParent();
12431 continue;
12432 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012433
Devang Patel7fe1dec2008-11-19 18:56:50 +000012434 // If there are two consecutive llvm.dbg.stoppoint calls then
12435 // it is likely that the optimizer deleted code in between these
12436 // two intrinsics.
12437 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12438 if (DBI_Next) {
12439 if (DBI_Prev
12440 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12441 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12442 IC.RemoveFromWorkList(DBI_Prev);
12443 DBI_Prev->eraseFromParent();
12444 }
12445 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012446 } else {
12447 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012448 }
12449
Chris Lattner2c7718a2007-03-23 19:17:18 +000012450 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012451 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012452
12453 // Recursively visit successors. If this is a branch or switch on a
12454 // constant, only visit the reachable successor.
12455 TerminatorInst *TI = BB->getTerminator();
12456 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12457 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12458 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012459 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012460 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012461 continue;
12462 }
12463 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12464 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12465 // See if this is an explicit destination.
12466 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12467 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012468 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012469 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012470 continue;
12471 }
12472
12473 // Otherwise it is the default destination.
12474 Worklist.push_back(SI->getSuccessor(0));
12475 continue;
12476 }
12477 }
12478
12479 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12480 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012481 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012482}
12483
Chris Lattnerec9c3582007-03-03 02:04:50 +000012484bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012485 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012486 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012487
12488 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12489 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012490
Chris Lattnerb3d59702005-07-07 20:40:38 +000012491 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012492 // Do a depth-first traversal of the function, populate the worklist with
12493 // the reachable instructions. Ignore blocks that are not reachable. Keep
12494 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012495 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012496 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012497
Chris Lattnerb3d59702005-07-07 20:40:38 +000012498 // Do a quick scan over the function. If we find any blocks that are
12499 // unreachable, remove any instructions inside of them. This prevents
12500 // the instcombine code from having to deal with some bad special cases.
12501 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12502 if (!Visited.count(BB)) {
12503 Instruction *Term = BB->getTerminator();
12504 while (Term != BB->begin()) { // Remove instrs bottom-up
12505 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012506
Bill Wendlingb7427032006-11-26 09:46:52 +000012507 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012508 ++NumDeadInst;
12509
12510 if (!I->use_empty())
12511 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12512 I->eraseFromParent();
Chris Lattner1e19d602009-01-31 07:04:22 +000012513 Changed = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012514 }
12515 }
12516 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012517
Chris Lattnerdbab3862007-03-02 21:28:56 +000012518 while (!Worklist.empty()) {
12519 Instruction *I = RemoveOneFromWorkList();
12520 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012521
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012522 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012523 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012524 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012525 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012526 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012527 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012528
Bill Wendlingb7427032006-11-26 09:46:52 +000012529 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012530
12531 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012532 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012533 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012534 continue;
12535 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012536
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012537 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012538 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012539 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012540
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012541 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012542 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012543 ReplaceInstUsesWith(*I, C);
12544
Chris Lattner62b14df2002-09-02 04:59:56 +000012545 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012546 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012547 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012548 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012549 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012550 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012551
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012552 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12553 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012554 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012556 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012557 if (NewC != CE) {
12558 i->set(NewC);
12559 Changed = true;
12560 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012561 }
12562
Chris Lattnerea1c4542004-12-08 23:43:58 +000012563 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012564 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012565 BasicBlock *BB = I->getParent();
12566 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12567 if (UserParent != BB) {
12568 bool UserIsSuccessor = false;
12569 // See if the user is one of our successors.
12570 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12571 if (*SI == UserParent) {
12572 UserIsSuccessor = true;
12573 break;
12574 }
12575
12576 // If the user is one of our immediate successors, and if that successor
12577 // only has us as a predecessors (we'd have to split the critical edge
12578 // otherwise), we can keep going.
12579 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12580 next(pred_begin(UserParent)) == pred_end(UserParent))
12581 // Okay, the CFG is simple enough, try to sink this instruction.
12582 Changed |= TryToSinkInstruction(I, UserParent);
12583 }
12584 }
12585
Chris Lattner8a2a3112001-12-14 16:52:21 +000012586 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012587#ifndef NDEBUG
12588 std::string OrigI;
12589#endif
12590 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012591 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012592 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012593 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012594 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012595 DOUT << "IC: Old = " << *I
12596 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012597
Chris Lattnerf523d062004-06-09 05:08:07 +000012598 // Everything uses the new instruction now.
12599 I->replaceAllUsesWith(Result);
12600
12601 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012602 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012603 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012604
Chris Lattner6934a042007-02-11 01:23:03 +000012605 // Move the name to the new instruction first.
12606 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012607
12608 // Insert the new instruction into the basic block...
12609 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012610 BasicBlock::iterator InsertPos = I;
12611
12612 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12613 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12614 ++InsertPos;
12615
12616 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012617
Chris Lattner00d51312004-05-01 23:27:23 +000012618 // Make sure that we reprocess all operands now that we reduced their
12619 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012620 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012621
Chris Lattnerf523d062004-06-09 05:08:07 +000012622 // Instructions can end up on the worklist more than once. Make sure
12623 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012624 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012625
12626 // Erase the old instruction.
12627 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012628 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012629#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012630 DOUT << "IC: Mod = " << OrigI
12631 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012632#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012633
Chris Lattner90ac28c2002-08-02 19:29:35 +000012634 // If the instruction was modified, it's possible that it is now dead.
12635 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012636 if (isInstructionTriviallyDead(I)) {
12637 // Make sure we process all operands now that we are reducing their
12638 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012639 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012640
Chris Lattner00d51312004-05-01 23:27:23 +000012641 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012642 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012643 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012644 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012645 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012646 AddToWorkList(I);
12647 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012648 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012649 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012650 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012651 }
12652 }
12653
Chris Lattnerec9c3582007-03-03 02:04:50 +000012654 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012655
12656 // Do an explicit clear, this shrinks the map if needed.
12657 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012658 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012659}
12660
Chris Lattnerec9c3582007-03-03 02:04:50 +000012661
12662bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012663 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12664
Chris Lattnerec9c3582007-03-03 02:04:50 +000012665 bool EverMadeChange = false;
12666
12667 // Iterate while there is work to do.
12668 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012669 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012670 EverMadeChange = true;
12671 return EverMadeChange;
12672}
12673
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012674FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012675 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012676}