blob: f6679452e194aa1ec47917a86573c631d132e3d4 [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
Chris Lattner867b99f2006-10-05 06:55:50 +0000355 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356 uint64_t &UndefElts, unsigned Depth = 0);
357
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
828 // If there are multiple uses of this value and we aren't at the root, then
829 // we can't do any simplifications of the operands, because DemandedMask
830 // only reflects the bits demanded by *one* of the users.
831 if (Depth != 0 && !I->hasOneUse()) {
832 // Compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
834 return 0;
835 }
836
837 // If this is the root being simplified, allow it to have multiple uses,
838 // just set the DemandedMask to all bits so that we can try to simplify the
839 // operands. This allows visitTruncInst (for example) to simplify the
840 // operand of a trunc without duplicating all the logic below.
841 if (Depth == 0 && !V->hasOneUse())
842 DemandedMask = APInt::getAllOnesValue(BitWidth);
843
Reid Spencer8cb68342007-03-12 17:25:59 +0000844 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
845 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
846 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000847 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000849 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000850 case Instruction::And:
851 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000852 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
853 RHSKnownZero, RHSKnownOne, Depth+1) ||
854 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000855 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000856 return I;
857 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
858 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000859
860 // If all of the demanded bits are known 1 on one side, return the other.
861 // These bits cannot contribute to the result of the 'and'.
862 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
863 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000864 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000865 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
866 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000867 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000868
869 // If all of the demanded bits in the inputs are known zeros, return zero.
870 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000871 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000872
873 // If the RHS is a constant, see if we can simplify it.
874 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000875 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000876
877 // Output known-1 bits are only known if set in both the LHS & RHS.
878 RHSKnownOne &= LHSKnownOne;
879 // Output known-0 are known to be clear if zero in either the LHS | RHS.
880 RHSKnownZero |= LHSKnownZero;
881 break;
882 case Instruction::Or:
883 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000884 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
885 RHSKnownZero, RHSKnownOne, Depth+1) ||
886 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000887 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000888 return I;
889 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
890 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000891
892 // If all of the demanded bits are known zero on one side, return the other.
893 // These bits cannot contribute to the result of the 'or'.
894 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
895 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000896 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000897 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
898 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000899 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000900
901 // If all of the potentially set bits on one side are known to be set on
902 // the other side, just use the 'other' side.
903 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
904 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000905 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000906 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
907 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000908 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000909
910 // If the RHS is a constant, see if we can simplify it.
911 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000913
914 // Output known-0 bits are only known if clear in both the LHS & RHS.
915 RHSKnownZero &= LHSKnownZero;
916 // Output known-1 are known to be set if set in either the LHS | RHS.
917 RHSKnownOne |= LHSKnownOne;
918 break;
919 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I;
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000927
928 // If all of the demanded bits are known zero on one side, return the other.
929 // These bits cannot contribute to the result of the 'xor'.
930 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // Output known-0 bits are known if clear or set in both the LHS & RHS.
936 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
937 (RHSKnownOne & LHSKnownOne);
938 // Output known-1 are known to be set if set in only one of the LHS, RHS.
939 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
940 (RHSKnownOne & LHSKnownZero);
941
942 // If all of the demanded bits are known to be zero on one side or the
943 // other, turn this into an *inclusive* or.
944 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
946 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000947 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000948 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000950 }
951
952 // If all of the demanded bits on one side are known, and all of the set
953 // bits on that side are also known to be set on the other side, turn this
954 // into an AND, as we know the bits will be cleared.
955 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
956 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
957 // all known
958 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
959 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
960 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000961 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 }
964 }
965
966 // If the RHS is a constant, see if we can simplify it.
967 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 RHSKnownZero = KnownZeroOut;
972 RHSKnownOne = KnownOneOut;
973 break;
974 }
975 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(1), 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 the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
986 ShrinkDemandedConstant(I, 2, DemandedMask))
987 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // Only known if known in both the LHS and RHS.
990 RHSKnownOne &= LHSKnownOne;
991 RHSKnownZero &= LHSKnownZero;
992 break;
993 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000994 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +0000995 DemandedMask.zext(truncBf);
996 RHSKnownZero.zext(truncBf);
997 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000998 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +0000999 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001001 DemandedMask.trunc(BitWidth);
1002 RHSKnownZero.trunc(BitWidth);
1003 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 break;
1006 }
1007 case Instruction::BitCast:
1008 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001009 return false; // vector->int or fp->int?
1010 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001011 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I;
1013 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 break;
1015 case Instruction::ZExt: {
1016 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001017 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001018
Zhou Shengd48653a2007-03-29 04:45:55 +00001019 DemandedMask.trunc(SrcBitWidth);
1020 RHSKnownZero.trunc(SrcBitWidth);
1021 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001022 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001023 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 DemandedMask.zext(BitWidth);
1026 RHSKnownZero.zext(BitWidth);
1027 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001030 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 break;
1032 }
1033 case Instruction::SExt: {
1034 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001036
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001038 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
Zhou Sheng01542f32007-03-29 02:26:30 +00001040 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 // If any of the sign extended bits are demanded, we know that the sign
1042 // bit is demanded.
1043 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001044 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
Zhou Shengd48653a2007-03-29 04:45:55 +00001046 InputDemandedBits.trunc(SrcBitWidth);
1047 RHSKnownZero.trunc(SrcBitWidth);
1048 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001050 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 InputDemandedBits.zext(BitWidth);
1053 RHSKnownZero.zext(BitWidth);
1054 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 // If the sign bit of the input is known set or clear, then we know the
1058 // top bits of the result.
1059
1060 // If the input sign bit is known zero, or if the NewBits are not demanded
1061 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1065 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001066 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 }
1069 break;
1070 }
1071 case Instruction::Add: {
1072 // Figure out what the input bits are. If the top bits of the and result
1073 // are not demanded, then the add doesn't demand them from its input
1074 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
1077 // If there is a constant on the RHS, there are a variety of xformations
1078 // we can do.
1079 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1080 // If null, this should be simplified elsewhere. Some of the xforms here
1081 // won't work if the RHS is zero.
1082 if (RHS->isZero())
1083 break;
1084
1085 // If the top bit of the output is demanded, demand everything from the
1086 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001087 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001088
1089 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001093
1094 // If the RHS of the add has bits set that can't affect the input, reduce
1095 // the constant.
1096 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001098
1099 // Avoid excess work.
1100 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1101 break;
1102
1103 // Turn it into OR if input bits are zero.
1104 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1105 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001106 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 }
1110
1111 // We can say something about the output known-zero and known-one bits,
1112 // depending on potential carries from the input constant and the
1113 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1114 // bits set and the RHS constant is 0x01001, then we know we have a known
1115 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1116
1117 // To compute this, we first compute the potential carry bits. These are
1118 // the bits which may be modified. I'm not aware of a better way to do
1119 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001121 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001122
1123 // Now that we know which bits have carries, compute the known-1/0 sets.
1124
1125 // Bits are known one if they are known zero in one operand and one in the
1126 // other, and there is no input carry.
1127 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1128 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1129
1130 // Bits are known zero if they are known zero in both operands and there
1131 // is no input carry.
1132 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1133 } else {
1134 // If the high-bits of this ADD are not demanded, then it does not demand
1135 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001136 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001137 // Right fill the mask of bits for this ADD to demand the most
1138 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001139 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1141 LHSKnownZero, LHSKnownOne, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 }
1146 }
1147 break;
1148 }
1149 case Instruction::Sub:
1150 // If the high-bits of this SUB are not demanded, then it does not demand
1151 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001152 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001153 // Right fill the mask of bits for this SUB to demand the most
1154 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001155 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001156 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1158 LHSKnownZero, LHSKnownOne, Depth+1) ||
1159 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001160 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001161 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001163 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1164 // the known zeros and ones.
1165 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 break;
1167 case Instruction::Shl:
1168 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001169 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001170 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return I;
1174 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 RHSKnownZero <<= ShiftAmt;
1176 RHSKnownOne <<= ShiftAmt;
1177 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001178 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001179 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001180 }
1181 break;
1182 case Instruction::LShr:
1183 // For a logical shift right
1184 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001185 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return I;
1192 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1194 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001195 if (ShiftAmt) {
1196 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001197 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001198 RHSKnownZero |= HighBits; // high bits known zero.
1199 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001200 }
1201 break;
1202 case Instruction::AShr:
1203 // If this is an arithmetic shift right and only the low-bit is set, we can
1204 // always convert this into a logical shr, even if the shift amount is
1205 // variable. The low bit of the shift cannot be an input sign bit unless
1206 // the shift amount is >= the size of the datatype, which is undefined.
1207 if (DemandedMask == 1) {
1208 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001213
1214 // If the sign bit is the only bit demanded by this ashr, then there is no
1215 // need to do it, the shift doesn't change the high bit.
1216 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
1219 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001220 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001221
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001224 // If any of the "high bits" are demanded, we should set the sign bit as
1225 // demanded.
1226 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001230 return I;
1231 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001234 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1235 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1236
1237 // Handle the sign bits.
1238 APInt SignBit(APInt::getSignBit(BitWidth));
1239 // Adjust to where it is now in the mask.
1240 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1241
1242 // If the input sign bit is known to be zero, or if none of the top bits
1243 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001244 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 (HighBits & ~DemandedMask) == HighBits) {
1246 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1251 RHSKnownOne |= HighBits;
1252 }
1253 }
1254 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001255 case Instruction::SRem:
1256 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001257 APInt RA = Rem->getValue().abs();
1258 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001259 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001260 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001261
Nick Lewycky8e394322008-11-02 02:41:50 +00001262 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001263 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001265 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001267
1268 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1269 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001270
1271 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001272
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001274 }
1275 }
1276 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001277 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001278 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1279 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001280 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1281 KnownZero2, KnownOne2, Depth+1) ||
1282 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001283 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001285
Chris Lattner455e9ab2009-01-21 18:09:24 +00001286 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001287 Leaders = std::max(Leaders,
1288 KnownZero2.countLeadingOnes());
1289 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001290 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001292 case Instruction::Call:
1293 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1294 switch (II->getIntrinsicID()) {
1295 default: break;
1296 case Intrinsic::bswap: {
1297 // If the only bits demanded come from one byte of the bswap result,
1298 // just shift the input byte into position to eliminate the bswap.
1299 unsigned NLZ = DemandedMask.countLeadingZeros();
1300 unsigned NTZ = DemandedMask.countTrailingZeros();
1301
1302 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1303 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1304 // have 14 leading zeros, round to 8.
1305 NLZ &= ~7;
1306 NTZ &= ~7;
1307 // If we need exactly one byte, we can do this transformation.
1308 if (BitWidth-NLZ-NTZ == 8) {
1309 unsigned ResultBit = NTZ;
1310 unsigned InputBit = BitWidth-NTZ-8;
1311
1312 // Replace this with either a left or right shift to get the byte into
1313 // the right place.
1314 Instruction *NewVal;
1315 if (InputBit > ResultBit)
1316 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1317 ConstantInt::get(I->getType(), InputBit-ResultBit));
1318 else
1319 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1320 ConstantInt::get(I->getType(), ResultBit-InputBit));
1321 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001323 }
1324
1325 // TODO: Could compute known zero/one bits based on the input.
1326 break;
1327 }
1328 }
1329 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001330 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001331 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001332 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001333
1334 // If the client is only demanding bits that we know, return the known
1335 // constant.
1336 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 return false;
1339}
1340
Chris Lattner867b99f2006-10-05 06:55:50 +00001341
Mon P Wangaeb06d22008-11-10 04:46:22 +00001342/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner867b99f2006-10-05 06:55:50 +00001343/// 64 or fewer elements. DemandedElts contains the set of elements that are
1344/// actually used by the caller. This method analyzes which elements of the
1345/// operand are undef and returns that information in UndefElts.
1346///
1347/// If the information about demanded elements can be used to simplify the
1348/// operation, the operation is simplified, then the resultant value is
1349/// returned. This returns null if no change was made.
1350Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1351 uint64_t &UndefElts,
1352 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001353 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001354 assert(VWidth <= 64 && "Vector too wide to analyze!");
1355 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001356 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001357
1358 if (isa<UndefValue>(V)) {
1359 // If the entire vector is undefined, just return this info.
1360 UndefElts = EltMask;
1361 return 0;
1362 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1363 UndefElts = EltMask;
1364 return UndefValue::get(V->getType());
1365 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001366
Chris Lattner867b99f2006-10-05 06:55:50 +00001367 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001368 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1369 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001370 Constant *Undef = UndefValue::get(EltTy);
1371
1372 std::vector<Constant*> Elts;
1373 for (unsigned i = 0; i != VWidth; ++i)
1374 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1375 Elts.push_back(Undef);
1376 UndefElts |= (1ULL << i);
1377 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1378 Elts.push_back(Undef);
1379 UndefElts |= (1ULL << i);
1380 } else { // Otherwise, defined.
1381 Elts.push_back(CP->getOperand(i));
1382 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001383
Chris Lattner867b99f2006-10-05 06:55:50 +00001384 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001385 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001386 return NewCP != CP ? NewCP : 0;
1387 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001388 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001389 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001390
1391 // Check if this is identity. If so, return 0 since we are not simplifying
1392 // anything.
1393 if (DemandedElts == ((1ULL << VWidth) -1))
1394 return 0;
1395
Reid Spencer9d6565a2007-02-15 02:26:10 +00001396 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001397 Constant *Zero = Constant::getNullValue(EltTy);
1398 Constant *Undef = UndefValue::get(EltTy);
1399 std::vector<Constant*> Elts;
1400 for (unsigned i = 0; i != VWidth; ++i)
1401 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1402 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001403 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001404 }
1405
Dan Gohman488fbfc2008-09-09 18:11:14 +00001406 // Limit search depth.
1407 if (Depth == 10)
1408 return false;
1409
1410 // If multiple users are using the root value, procede with
1411 // simplification conservatively assuming that all elements
1412 // are needed.
1413 if (!V->hasOneUse()) {
1414 // Quit if we find multiple users of a non-root value though.
1415 // They'll be handled when it's their turn to be visited by
1416 // the main instcombine process.
1417 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001418 // TODO: Just compute the UndefElts information recursively.
1419 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001420
1421 // Conservatively assume that all elements are needed.
1422 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001423 }
1424
1425 Instruction *I = dyn_cast<Instruction>(V);
1426 if (!I) return false; // Only analyze instructions.
1427
1428 bool MadeChange = false;
1429 uint64_t UndefElts2;
1430 Value *TmpV;
1431 switch (I->getOpcode()) {
1432 default: break;
1433
1434 case Instruction::InsertElement: {
1435 // If this is a variable index, we don't know which element it overwrites.
1436 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001437 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 if (Idx == 0) {
1439 // Note that we can't propagate undef elt info, because we don't know
1440 // which elt is getting updated.
1441 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1442 UndefElts2, Depth+1);
1443 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1444 break;
1445 }
1446
1447 // If this is inserting an element that isn't demanded, remove this
1448 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001449 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1451 return AddSoonDeadInstToWorklist(*I, 0);
1452
1453 // Otherwise, the element inserted overwrites whatever was there, so the
1454 // input demanded set is simpler than the output set.
1455 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1456 DemandedElts & ~(1ULL << IdxNo),
1457 UndefElts, Depth+1);
1458 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1459
1460 // The inserted element is defined.
Dan Gohman488fbfc2008-09-09 18:11:14 +00001461 UndefElts &= ~(1ULL << IdxNo);
1462 break;
1463 }
1464 case Instruction::ShuffleVector: {
1465 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001466 uint64_t LHSVWidth =
1467 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman488fbfc2008-09-09 18:11:14 +00001468 uint64_t LeftDemanded = 0, RightDemanded = 0;
1469 for (unsigned i = 0; i < VWidth; i++) {
1470 if (DemandedElts & (1ULL << i)) {
1471 unsigned MaskVal = Shuffle->getMaskValue(i);
1472 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001473 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001474 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001475 if (MaskVal < LHSVWidth)
Dan Gohman488fbfc2008-09-09 18:11:14 +00001476 LeftDemanded |= 1ULL << MaskVal;
1477 else
Mon P Wangaeb06d22008-11-10 04:46:22 +00001478 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001479 }
1480 }
1481 }
1482
1483 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1484 UndefElts2, Depth+1);
1485 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1486
1487 uint64_t UndefElts3;
1488 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1489 UndefElts3, Depth+1);
1490 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1491
1492 bool NewUndefElts = false;
1493 for (unsigned i = 0; i < VWidth; i++) {
1494 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001495 if (MaskVal == -1u) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001496 uint64_t NewBit = 1ULL << i;
1497 UndefElts |= NewBit;
Mon P Wangaeb06d22008-11-10 04:46:22 +00001498 } else if (MaskVal < LHSVWidth) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001499 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1500 NewUndefElts |= NewBit;
1501 UndefElts |= NewBit;
1502 } else {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001503 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001504 NewUndefElts |= NewBit;
1505 UndefElts |= NewBit;
1506 }
1507 }
1508
1509 if (NewUndefElts) {
1510 // Add additional discovered undefs.
1511 std::vector<Constant*> Elts;
1512 for (unsigned i = 0; i < VWidth; ++i) {
1513 if (UndefElts & (1ULL << i))
1514 Elts.push_back(UndefValue::get(Type::Int32Ty));
1515 else
1516 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1517 Shuffle->getMaskValue(i)));
1518 }
1519 I->setOperand(2, ConstantVector::get(Elts));
1520 MadeChange = true;
1521 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 break;
1523 }
Chris Lattner69878332007-04-14 22:29:23 +00001524 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001525 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001526 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1527 if (!VTy) break;
1528 unsigned InVWidth = VTy->getNumElements();
1529 uint64_t InputDemandedElts = 0;
1530 unsigned Ratio;
1531
1532 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001533 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001534 // elements as are demanded of us.
1535 Ratio = 1;
1536 InputDemandedElts = DemandedElts;
1537 } else if (VWidth > InVWidth) {
1538 // Untested so far.
1539 break;
1540
1541 // If there are more elements in the result than there are in the source,
1542 // then an input element is live if any of the corresponding output
1543 // elements are live.
1544 Ratio = VWidth/InVWidth;
1545 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1546 if (DemandedElts & (1ULL << OutIdx))
1547 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1548 }
1549 } else {
1550 // Untested so far.
1551 break;
1552
1553 // If there are more elements in the source than there are in the result,
1554 // then an input element is live if the corresponding output element is
1555 // live.
1556 Ratio = InVWidth/VWidth;
1557 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1558 if (DemandedElts & (1ULL << InIdx/Ratio))
1559 InputDemandedElts |= 1ULL << InIdx;
1560 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001561
Chris Lattner69878332007-04-14 22:29:23 +00001562 // div/rem demand all inputs, because they don't want divide by zero.
1563 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1564 UndefElts2, Depth+1);
1565 if (TmpV) {
1566 I->setOperand(0, TmpV);
1567 MadeChange = true;
1568 }
1569
1570 UndefElts = UndefElts2;
1571 if (VWidth > InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the result than there are in the source,
1574 // then an output element is undef if the corresponding input element is
1575 // undef.
1576 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1577 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1578 UndefElts |= 1ULL << OutIdx;
1579 } else if (VWidth < InVWidth) {
1580 assert(0 && "Unimp");
1581 // If there are more elements in the source than there are in the result,
1582 // then a result element is undef if all of the corresponding input
1583 // elements are undef.
1584 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1585 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1586 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1587 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1588 }
1589 break;
1590 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001591 case Instruction::And:
1592 case Instruction::Or:
1593 case Instruction::Xor:
1594 case Instruction::Add:
1595 case Instruction::Sub:
1596 case Instruction::Mul:
1597 // div/rem demand all inputs, because they don't want divide by zero.
1598 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1599 UndefElts, Depth+1);
1600 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1601 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1602 UndefElts2, Depth+1);
1603 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1604
1605 // Output elements are undefined if both are undefined. Consider things
1606 // like undef&0. The result is known zero, not undef.
1607 UndefElts &= UndefElts2;
1608 break;
1609
1610 case Instruction::Call: {
1611 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1612 if (!II) break;
1613 switch (II->getIntrinsicID()) {
1614 default: break;
1615
1616 // Binary vector operations that work column-wise. A dest element is a
1617 // function of the corresponding input elements from the two inputs.
1618 case Intrinsic::x86_sse_sub_ss:
1619 case Intrinsic::x86_sse_mul_ss:
1620 case Intrinsic::x86_sse_min_ss:
1621 case Intrinsic::x86_sse_max_ss:
1622 case Intrinsic::x86_sse2_sub_sd:
1623 case Intrinsic::x86_sse2_mul_sd:
1624 case Intrinsic::x86_sse2_min_sd:
1625 case Intrinsic::x86_sse2_max_sd:
1626 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1627 UndefElts, Depth+1);
1628 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1629 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1630 UndefElts2, Depth+1);
1631 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1632
1633 // If only the low elt is demanded and this is a scalarizable intrinsic,
1634 // scalarize it now.
1635 if (DemandedElts == 1) {
1636 switch (II->getIntrinsicID()) {
1637 default: break;
1638 case Intrinsic::x86_sse_sub_ss:
1639 case Intrinsic::x86_sse_mul_ss:
1640 case Intrinsic::x86_sse2_sub_sd:
1641 case Intrinsic::x86_sse2_mul_sd:
1642 // TODO: Lower MIN/MAX/ABS/etc
1643 Value *LHS = II->getOperand(1);
1644 Value *RHS = II->getOperand(2);
1645 // Extract the element as scalars.
1646 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1647 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1648
1649 switch (II->getIntrinsicID()) {
1650 default: assert(0 && "Case stmts out of sync!");
1651 case Intrinsic::x86_sse_sub_ss:
1652 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001653 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001654 II->getName()), *II);
1655 break;
1656 case Intrinsic::x86_sse_mul_ss:
1657 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001658 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001659 II->getName()), *II);
1660 break;
1661 }
1662
1663 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001664 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1665 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001666 InsertNewInstBefore(New, *II);
1667 AddSoonDeadInstToWorklist(*II, 0);
1668 return New;
1669 }
1670 }
1671
1672 // Output elements are undefined if both are undefined. Consider things
1673 // like undef&0. The result is known zero, not undef.
1674 UndefElts &= UndefElts2;
1675 break;
1676 }
1677 break;
1678 }
1679 }
1680 return MadeChange ? I : 0;
1681}
1682
Dan Gohman45b4e482008-05-19 22:14:15 +00001683
Chris Lattner564a7272003-08-13 19:01:45 +00001684/// AssociativeOpt - Perform an optimization on an associative operator. This
1685/// function is designed to check a chain of associative operators for a
1686/// potential to apply a certain optimization. Since the optimization may be
1687/// applicable if the expression was reassociated, this checks the chain, then
1688/// reassociates the expression as necessary to expose the optimization
1689/// opportunity. This makes use of a special Functor, which must define
1690/// 'shouldApply' and 'apply' methods.
1691///
1692template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001693static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001694 unsigned Opcode = Root.getOpcode();
1695 Value *LHS = Root.getOperand(0);
1696
1697 // Quick check, see if the immediate LHS matches...
1698 if (F.shouldApply(LHS))
1699 return F.apply(Root);
1700
1701 // Otherwise, if the LHS is not of the same opcode as the root, return.
1702 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001703 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001704 // Should we apply this transform to the RHS?
1705 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1706
1707 // If not to the RHS, check to see if we should apply to the LHS...
1708 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1709 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1710 ShouldApply = true;
1711 }
1712
1713 // If the functor wants to apply the optimization to the RHS of LHSI,
1714 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1715 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001716 // Now all of the instructions are in the current basic block, go ahead
1717 // and perform the reassociation.
1718 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1719
1720 // First move the selected RHS to the LHS of the root...
1721 Root.setOperand(0, LHSI->getOperand(1));
1722
1723 // Make what used to be the LHS of the root be the user of the root...
1724 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001725 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001726 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1727 return 0;
1728 }
Chris Lattner65725312004-04-16 18:08:07 +00001729 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001730 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001731 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001732 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001733 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001734
1735 // Now propagate the ExtraOperand down the chain of instructions until we
1736 // get to LHSI.
1737 while (TmpLHSI != LHSI) {
1738 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001739 // Move the instruction to immediately before the chain we are
1740 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001741 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001742 ARI = NextLHSI;
1743
Chris Lattner564a7272003-08-13 19:01:45 +00001744 Value *NextOp = NextLHSI->getOperand(1);
1745 NextLHSI->setOperand(1, ExtraOperand);
1746 TmpLHSI = NextLHSI;
1747 ExtraOperand = NextOp;
1748 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001749
Chris Lattner564a7272003-08-13 19:01:45 +00001750 // Now that the instructions are reassociated, have the functor perform
1751 // the transformation...
1752 return F.apply(Root);
1753 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001754
Chris Lattner564a7272003-08-13 19:01:45 +00001755 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1756 }
1757 return 0;
1758}
1759
Dan Gohman844731a2008-05-13 00:00:25 +00001760namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001761
Nick Lewycky02d639f2008-05-23 04:34:58 +00001762// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001763struct AddRHS {
1764 Value *RHS;
1765 AddRHS(Value *rhs) : RHS(rhs) {}
1766 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1767 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001768 return BinaryOperator::CreateShl(Add.getOperand(0),
1769 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001770 }
1771};
1772
1773// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1774// iff C1&C2 == 0
1775struct AddMaskingAnd {
1776 Constant *C2;
1777 AddMaskingAnd(Constant *c) : C2(c) {}
1778 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001779 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001780 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001781 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001782 }
1783 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001784 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001785 }
1786};
1787
Dan Gohman844731a2008-05-13 00:00:25 +00001788}
1789
Chris Lattner6e7ba452005-01-01 16:22:27 +00001790static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001791 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001792 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001793 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001794 }
1795
Chris Lattner2eefe512004-04-09 19:05:30 +00001796 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001797 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1798 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001799
Chris Lattner2eefe512004-04-09 19:05:30 +00001800 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1801 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001802 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1803 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001804 }
1805
1806 Value *Op0 = SO, *Op1 = ConstOperand;
1807 if (!ConstIsRHS)
1808 std::swap(Op0, Op1);
1809 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001811 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001812 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001813 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001814 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001815 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001816 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001817 abort();
1818 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001819 return IC->InsertNewInstBefore(New, I);
1820}
1821
1822// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1823// constant as the other operand, try to fold the binary operator into the
1824// select arguments. This also works for Cast instructions, which obviously do
1825// not have a second operand.
1826static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1827 InstCombiner *IC) {
1828 // Don't modify shared select instructions
1829 if (!SI->hasOneUse()) return 0;
1830 Value *TV = SI->getOperand(1);
1831 Value *FV = SI->getOperand(2);
1832
1833 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001834 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001835 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001836
Chris Lattner6e7ba452005-01-01 16:22:27 +00001837 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1838 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1839
Gabor Greif051a9502008-04-06 20:25:17 +00001840 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1841 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001842 }
1843 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001844}
1845
Chris Lattner4e998b22004-09-29 05:07:12 +00001846
1847/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1848/// node as operand #0, see if we can fold the instruction into the PHI (which
1849/// is only possible if all operands to the PHI are constants).
1850Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1851 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001852 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001853 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001854
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001855 // Check to see if all of the operands of the PHI are constants. If there is
1856 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001857 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001858 BasicBlock *NonConstBB = 0;
1859 for (unsigned i = 0; i != NumPHIValues; ++i)
1860 if (!isa<Constant>(PN->getIncomingValue(i))) {
1861 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001862 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001863 NonConstBB = PN->getIncomingBlock(i);
1864
1865 // If the incoming non-constant value is in I's block, we have an infinite
1866 // loop.
1867 if (NonConstBB == I.getParent())
1868 return 0;
1869 }
1870
1871 // If there is exactly one non-constant value, we can insert a copy of the
1872 // operation in that block. However, if this is a critical edge, we would be
1873 // inserting the computation one some other paths (e.g. inside a loop). Only
1874 // do this if the pred block is unconditionally branching into the phi block.
1875 if (NonConstBB) {
1876 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1877 if (!BI || !BI->isUnconditional()) return 0;
1878 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001879
1880 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001881 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001882 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001883 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001884 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001885
1886 // Next, add all of the operands to the PHI.
1887 if (I.getNumOperands() == 2) {
1888 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001889 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001890 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001891 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001892 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1893 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1894 else
1895 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001896 } else {
1897 assert(PN->getIncomingBlock(i) == NonConstBB);
1898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001899 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001900 PN->getIncomingValue(i), C, "phitmp",
1901 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001902 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001903 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001904 CI->getPredicate(),
1905 PN->getIncomingValue(i), C, "phitmp",
1906 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001907 else
1908 assert(0 && "Unknown binop!");
1909
Chris Lattnerdbab3862007-03-02 21:28:56 +00001910 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001911 }
1912 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001913 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001914 } else {
1915 CastInst *CI = cast<CastInst>(&I);
1916 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001917 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001918 Value *InV;
1919 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001920 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001921 } else {
1922 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001923 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001924 I.getType(), "phitmp",
1925 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001926 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001927 }
1928 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001929 }
1930 }
1931 return ReplaceInstUsesWith(I, NewPN);
1932}
1933
Chris Lattner2454a2e2008-01-29 06:52:45 +00001934
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001935/// WillNotOverflowSignedAdd - Return true if we can prove that:
1936/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1937/// This basically requires proving that the add in the original type would not
1938/// overflow to change the sign bit or have a carry out.
1939bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1940 // There are different heuristics we can use for this. Here are some simple
1941 // ones.
1942
1943 // Add has the property that adding any two 2's complement numbers can only
1944 // have one carry bit which can change a sign. As such, if LHS and RHS each
1945 // have at least two sign bits, we know that the addition of the two values will
1946 // sign extend fine.
1947 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1948 return true;
1949
1950
1951 // If one of the operands only has one non-zero bit, and if the other operand
1952 // has a known-zero bit in a more significant place than it (not including the
1953 // sign bit) the ripple may go up to and fill the zero, but won't change the
1954 // sign. For example, (X & ~4) + 1.
1955
1956 // TODO: Implement.
1957
1958 return false;
1959}
1960
Chris Lattner2454a2e2008-01-29 06:52:45 +00001961
Chris Lattner7e708292002-06-25 16:13:24 +00001962Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001963 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001964 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001965
Chris Lattner66331a42004-04-10 22:01:55 +00001966 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001967 // X + undef -> undef
1968 if (isa<UndefValue>(RHS))
1969 return ReplaceInstUsesWith(I, RHS);
1970
Chris Lattner66331a42004-04-10 22:01:55 +00001971 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001972 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001973 if (RHSC->isNullValue())
1974 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001975 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001976 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1977 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001978 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001979 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001980
Chris Lattner66331a42004-04-10 22:01:55 +00001981 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001982 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001983 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001984 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001985 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001986 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001987
1988 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1989 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00001990 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
1991 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00001992
1993 // zext(i1) - 1 -> select i1, 0, -1
1994 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1995 if (CI->isAllOnesValue() &&
1996 ZI->getOperand(0)->getType() == Type::Int1Ty)
1997 return SelectInst::Create(ZI->getOperand(0),
1998 Constant::getNullValue(I.getType()),
1999 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002000 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002001
2002 if (isa<PHINode>(LHS))
2003 if (Instruction *NV = FoldOpIntoPhi(I))
2004 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002005
Chris Lattner4f637d42006-01-06 17:59:59 +00002006 ConstantInt *XorRHS = 0;
2007 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002008 if (isa<ConstantInt>(RHSC) &&
2009 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002010 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002011 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002012
Zhou Sheng4351c642007-04-02 08:20:41 +00002013 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002014 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2015 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002016 do {
2017 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002018 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2019 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002020 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2021 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002022 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002023 if (!MaskedValueIsZero(XorLHS,
2024 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002025 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002026 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002027 }
2028 }
2029 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002030 C0080Val = APIntOps::lshr(C0080Val, Size);
2031 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2032 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002033
Reid Spencer35c38852007-03-28 01:36:16 +00002034 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002035 // with funny bit widths then this switch statement should be removed. It
2036 // is just here to get the size of the "middle" type back up to something
2037 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002038 const Type *MiddleType = 0;
2039 switch (Size) {
2040 default: break;
2041 case 32: MiddleType = Type::Int32Ty; break;
2042 case 16: MiddleType = Type::Int16Ty; break;
2043 case 8: MiddleType = Type::Int8Ty; break;
2044 }
2045 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002046 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002047 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002048 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002049 }
2050 }
Chris Lattner66331a42004-04-10 22:01:55 +00002051 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002052
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002053 if (I.getType() == Type::Int1Ty)
2054 return BinaryOperator::CreateXor(LHS, RHS);
2055
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002056 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002057 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002058 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002059
2060 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2061 if (RHSI->getOpcode() == Instruction::Sub)
2062 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2063 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2064 }
2065 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2066 if (LHSI->getOpcode() == Instruction::Sub)
2067 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2068 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2069 }
Robert Bocchino71698282004-07-27 21:02:21 +00002070 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002071
Chris Lattner5c4afb92002-05-08 22:46:53 +00002072 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002073 // -A + -B --> -(A + B)
2074 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002075 if (LHS->getType()->isIntOrIntVector()) {
2076 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002077 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002078 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002079 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002080 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002081 }
2082
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002083 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002084 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002085
2086 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002087 if (!isa<Constant>(RHS))
2088 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002089 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002090
Misha Brukmanfd939082005-04-21 23:48:37 +00002091
Chris Lattner50af16a2004-11-13 19:50:12 +00002092 ConstantInt *C2;
2093 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2094 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002095 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002096
2097 // X*C1 + X*C2 --> X * (C1+C2)
2098 ConstantInt *C1;
2099 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002100 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002101 }
2102
2103 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002104 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002105 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002106
Chris Lattnere617c9e2007-01-05 02:17:46 +00002107 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002108 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2109 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002110
Chris Lattnerad3448c2003-02-18 19:57:07 +00002111
Chris Lattner564a7272003-08-13 19:01:45 +00002112 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002113 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002114 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2115 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002116
2117 // A+B --> A|B iff A and B have no bits set in common.
2118 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2119 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2120 APInt LHSKnownOne(IT->getBitWidth(), 0);
2121 APInt LHSKnownZero(IT->getBitWidth(), 0);
2122 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2123 if (LHSKnownZero != 0) {
2124 APInt RHSKnownOne(IT->getBitWidth(), 0);
2125 APInt RHSKnownZero(IT->getBitWidth(), 0);
2126 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2127
2128 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002129 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002130 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002131 }
2132 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002133
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002134 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002135 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002136 Value *W, *X, *Y, *Z;
2137 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2138 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2139 if (W != Y) {
2140 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002141 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002142 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002143 std::swap(W, X);
2144 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002145 std::swap(Y, Z);
2146 std::swap(W, X);
2147 }
2148 }
2149
2150 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002151 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002152 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002153 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002154 }
2155 }
2156 }
2157
Chris Lattner6b032052003-10-02 15:11:26 +00002158 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002159 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002160 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002162
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002163 // (X & FF00) + xx00 -> (X+xx00) & FF00
2164 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002165 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002166 if (Anded == CRHS) {
2167 // See if all bits from the first bit set in the Add RHS up are included
2168 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002169 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002170
2171 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002172 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002173
2174 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002175 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002176
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002177 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2178 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002180 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002181 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002182 }
2183 }
2184 }
2185
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002186 // Try to fold constant add into select arguments.
2187 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002188 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002189 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002190 }
2191
Reid Spencer1628cec2006-10-26 06:15:43 +00002192 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002193 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002194 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002195 CastInst *CI = dyn_cast<CastInst>(LHS);
2196 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002197 if (!CI) {
2198 CI = dyn_cast<CastInst>(RHS);
2199 Other = LHS;
2200 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002201 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002202 (CI->getType()->getPrimitiveSizeInBits() ==
2203 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002204 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002205 unsigned AS =
2206 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002207 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2208 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002209 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002210 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002211 }
2212 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002213
Chris Lattner42790482007-12-20 01:56:58 +00002214 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002215 {
2216 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002217 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002218 if (!SI) {
2219 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002220 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002221 }
Chris Lattner42790482007-12-20 01:56:58 +00002222 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002223 Value *TV = SI->getTrueValue();
2224 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002225 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002226
2227 // Can we fold the add into the argument of the select?
2228 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002229 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2230 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002231 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002232 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2233 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002234 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002235 }
2236 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002237
2238 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2239 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2240 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2241 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002242
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002243 // Check for (add (sext x), y), see if we can merge this into an
2244 // integer add followed by a sext.
2245 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2246 // (add (sext x), cst) --> (sext (add x, cst'))
2247 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2248 Constant *CI =
2249 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2250 if (LHSConv->hasOneUse() &&
2251 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2252 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2253 // Insert the new, smaller add.
2254 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2255 CI, "addconv");
2256 InsertNewInstBefore(NewAdd, I);
2257 return new SExtInst(NewAdd, I.getType());
2258 }
2259 }
2260
2261 // (add (sext x), (sext y)) --> (sext (add int x, y))
2262 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2263 // Only do this if x/y have the same type, if at last one of them has a
2264 // single use (so we don't increase the number of sexts), and if the
2265 // integer add will not overflow.
2266 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2267 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2268 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2269 RHSConv->getOperand(0))) {
2270 // Insert the new integer add.
2271 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2272 RHSConv->getOperand(0),
2273 "addconv");
2274 InsertNewInstBefore(NewAdd, I);
2275 return new SExtInst(NewAdd, I.getType());
2276 }
2277 }
2278 }
2279
2280 // Check for (add double (sitofp x), y), see if we can merge this into an
2281 // integer add followed by a promotion.
2282 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2283 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2284 // ... if the constant fits in the integer value. This is useful for things
2285 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2286 // requires a constant pool load, and generally allows the add to be better
2287 // instcombined.
2288 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2289 Constant *CI =
2290 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2291 if (LHSConv->hasOneUse() &&
2292 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2293 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2294 // Insert the new integer add.
2295 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2296 CI, "addconv");
2297 InsertNewInstBefore(NewAdd, I);
2298 return new SIToFPInst(NewAdd, I.getType());
2299 }
2300 }
2301
2302 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2303 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2304 // Only do this if x/y have the same type, if at last one of them has a
2305 // single use (so we don't increase the number of int->fp conversions),
2306 // and if the integer add will not overflow.
2307 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2308 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2309 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2310 RHSConv->getOperand(0))) {
2311 // Insert the new integer add.
2312 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2313 RHSConv->getOperand(0),
2314 "addconv");
2315 InsertNewInstBefore(NewAdd, I);
2316 return new SIToFPInst(NewAdd, I.getType());
2317 }
2318 }
2319 }
2320
Chris Lattner7e708292002-06-25 16:13:24 +00002321 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002322}
2323
Chris Lattner7e708292002-06-25 16:13:24 +00002324Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002325 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002326
Chris Lattnerd137ab42008-07-17 06:07:20 +00002327 if (Op0 == Op1 && // sub X, X -> 0
2328 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002330
Chris Lattner233f7dc2002-08-12 21:17:25 +00002331 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002332 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002333 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002334
Chris Lattnere87597f2004-10-16 18:11:37 +00002335 if (isa<UndefValue>(Op0))
2336 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2337 if (isa<UndefValue>(Op1))
2338 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2339
Chris Lattnerd65460f2003-11-05 01:06:05 +00002340 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2341 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002342 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002344
Chris Lattnerd65460f2003-11-05 01:06:05 +00002345 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002346 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002347 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002348 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002349
Chris Lattner76b7a062007-01-15 07:02:54 +00002350 // -(X >>u 31) -> (X >>s 31)
2351 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002352 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002353 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002354 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002355 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002356 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002357 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002358 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002359 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002360 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002361 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002362 }
2363 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002364 }
2365 else if (SI->getOpcode() == Instruction::AShr) {
2366 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2367 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002368 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002369 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002370 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002371 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002372 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002373 }
2374 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002375 }
2376 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002377 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002378
2379 // Try to fold constant sub into select arguments.
2380 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002382 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002383 }
2384
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002385 if (I.getType() == Type::Int1Ty)
2386 return BinaryOperator::CreateXor(Op0, Op1);
2387
Chris Lattner43d84d62005-04-07 16:15:25 +00002388 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2389 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002390 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002391 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002392 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002393 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002394 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002395 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2396 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2397 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002398 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002399 Op1I->getOperand(0));
2400 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002401 }
2402
Chris Lattnerfd059242003-10-15 16:48:29 +00002403 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002404 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2405 // is not used by anyone else...
2406 //
Chris Lattner0517e722004-02-02 20:09:56 +00002407 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002408 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002409 // Swap the two operands of the subexpr...
2410 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2411 Op1I->setOperand(0, IIOp1);
2412 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002413
Chris Lattnera2881962003-02-18 19:28:33 +00002414 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002415 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002416 }
2417
2418 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2419 //
2420 if (Op1I->getOpcode() == Instruction::And &&
2421 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2422 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2423
Chris Lattnerf523d062004-06-09 05:08:07 +00002424 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002425 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2426 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002427 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002428
Reid Spencerac5209e2006-10-16 23:08:08 +00002429 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002430 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002431 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002432 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002433 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002434 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002435 ConstantExpr::getNeg(DivRHS));
2436
Chris Lattnerad3448c2003-02-18 19:57:07 +00002437 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002438 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002439 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002440 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002441 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002442 }
Chris Lattner40371712002-05-09 01:29:19 +00002443 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002444 }
Chris Lattnera2881962003-02-18 19:28:33 +00002445
Chris Lattner9919e3d2006-12-02 00:13:08 +00002446 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002447 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002448 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002449 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2450 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2451 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2452 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002453 } else if (Op0I->getOpcode() == Instruction::Sub) {
2454 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002455 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002456 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002457 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002458
Chris Lattner50af16a2004-11-13 19:50:12 +00002459 ConstantInt *C1;
2460 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002461 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002463
Chris Lattner50af16a2004-11-13 19:50:12 +00002464 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2465 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002466 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002467 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002468 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002469}
2470
Chris Lattnera0141b92007-07-15 20:42:37 +00002471/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2472/// comparison only checks the sign bit. If it only checks the sign bit, set
2473/// TrueIfSigned if the result of the comparison is true when the input value is
2474/// signed.
2475static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2476 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002477 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002478 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2479 TrueIfSigned = true;
2480 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002481 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2482 TrueIfSigned = true;
2483 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002484 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2485 TrueIfSigned = false;
2486 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002487 case ICmpInst::ICMP_UGT:
2488 // True if LHS u> RHS and RHS == high-bit-mask - 1
2489 TrueIfSigned = true;
2490 return RHS->getValue() ==
2491 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2492 case ICmpInst::ICMP_UGE:
2493 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2494 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002495 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002496 default:
2497 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002498 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002499}
2500
Chris Lattner7e708292002-06-25 16:13:24 +00002501Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002502 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002503 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002504
Chris Lattnere87597f2004-10-16 18:11:37 +00002505 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2506 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2507
Chris Lattner233f7dc2002-08-12 21:17:25 +00002508 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002509 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2510 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002511
2512 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002513 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002514 if (SI->getOpcode() == Instruction::Shl)
2515 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002517 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002518
Zhou Sheng843f07672007-04-19 05:39:12 +00002519 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002520 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2521 if (CI->equalsInt(1)) // X * 1 == X
2522 return ReplaceInstUsesWith(I, Op0);
2523 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002525
Zhou Sheng97b52c22007-03-29 01:57:21 +00002526 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002527 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002528 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002529 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002530 }
Robert Bocchino71698282004-07-27 21:02:21 +00002531 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002532 if (Op1F->isNullValue())
2533 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002534
Chris Lattnera2881962003-02-18 19:28:33 +00002535 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2536 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002537 if (Op1F->isExactlyValue(1.0))
2538 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2539 } else if (isa<VectorType>(Op1->getType())) {
2540 if (isa<ConstantAggregateZero>(Op1))
2541 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002542
2543 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2544 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2545 return BinaryOperator::CreateNeg(Op0, I.getName());
2546
2547 // As above, vector X*splat(1.0) -> X in all defined cases.
2548 if (Constant *Splat = Op1V->getSplatValue()) {
2549 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2550 if (F->isExactlyValue(1.0))
2551 return ReplaceInstUsesWith(I, Op0);
2552 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2553 if (CI->equalsInt(1))
2554 return ReplaceInstUsesWith(I, Op0);
2555 }
2556 }
Chris Lattnera2881962003-02-18 19:28:33 +00002557 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002558
2559 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2560 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002561 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002562 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002563 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002564 Op1, "tmp");
2565 InsertNewInstBefore(Add, I);
2566 Value *C1C2 = ConstantExpr::getMul(Op1,
2567 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002569
2570 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002571
2572 // Try to fold constant mul into select arguments.
2573 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002574 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002575 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002576
2577 if (isa<PHINode>(Op0))
2578 if (Instruction *NV = FoldOpIntoPhi(I))
2579 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002580 }
2581
Chris Lattnera4f445b2003-03-10 23:23:04 +00002582 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2583 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002584 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002585
Nick Lewycky0c730792008-11-21 07:33:58 +00002586 // (X / Y) * Y = X - (X % Y)
2587 // (X / Y) * -Y = (X % Y) - X
2588 {
2589 Value *Op1 = I.getOperand(1);
2590 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2591 if (!BO ||
2592 (BO->getOpcode() != Instruction::UDiv &&
2593 BO->getOpcode() != Instruction::SDiv)) {
2594 Op1 = Op0;
2595 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2596 }
2597 Value *Neg = dyn_castNegVal(Op1);
2598 if (BO && BO->hasOneUse() &&
2599 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2600 (BO->getOpcode() == Instruction::UDiv ||
2601 BO->getOpcode() == Instruction::SDiv)) {
2602 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2603
2604 Instruction *Rem;
2605 if (BO->getOpcode() == Instruction::UDiv)
2606 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2607 else
2608 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2609
2610 InsertNewInstBefore(Rem, I);
2611 Rem->takeName(BO);
2612
2613 if (Op1BO == Op1)
2614 return BinaryOperator::CreateSub(Op0BO, Rem);
2615 else
2616 return BinaryOperator::CreateSub(Rem, Op0BO);
2617 }
2618 }
2619
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002620 if (I.getType() == Type::Int1Ty)
2621 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2622
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002623 // If one of the operands of the multiply is a cast from a boolean value, then
2624 // we know the bool is either zero or one, so this is a 'masking' multiply.
2625 // See if we can simplify things based on how the boolean was originally
2626 // formed.
2627 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002628 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002629 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002630 BoolCast = CI;
2631 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002632 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002633 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002634 BoolCast = CI;
2635 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002636 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002637 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2638 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002639 bool TIS = false;
2640
Reid Spencere4d87aa2006-12-23 06:05:41 +00002641 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002642 // multiply into a shift/and combination.
2643 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002644 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2645 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002646 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002647 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002648 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002649 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002650 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002651 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002652 BoolCast->getOperand(0)->getName()+
2653 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002654
2655 // If the multiply type is not the same as the source type, sign extend
2656 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002657 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002658 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2659 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002660 Instruction::CastOps opcode =
2661 (SrcBits == DstBits ? Instruction::BitCast :
2662 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2663 V = InsertCastBefore(opcode, V, I.getType(), I);
2664 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002665
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002666 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002668 }
2669 }
2670 }
2671
Chris Lattner7e708292002-06-25 16:13:24 +00002672 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002673}
2674
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002675/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2676/// instruction.
2677bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2678 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2679
2680 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2681 int NonNullOperand = -1;
2682 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2683 if (ST->isNullValue())
2684 NonNullOperand = 2;
2685 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2686 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2687 if (ST->isNullValue())
2688 NonNullOperand = 1;
2689
2690 if (NonNullOperand == -1)
2691 return false;
2692
2693 Value *SelectCond = SI->getOperand(0);
2694
2695 // Change the div/rem to use 'Y' instead of the select.
2696 I.setOperand(1, SI->getOperand(NonNullOperand));
2697
2698 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2699 // problem. However, the select, or the condition of the select may have
2700 // multiple uses. Based on our knowledge that the operand must be non-zero,
2701 // propagate the known value for the select into other uses of it, and
2702 // propagate a known value of the condition into its other users.
2703
2704 // If the select and condition only have a single use, don't bother with this,
2705 // early exit.
2706 if (SI->use_empty() && SelectCond->hasOneUse())
2707 return true;
2708
2709 // Scan the current block backward, looking for other uses of SI.
2710 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2711
2712 while (BBI != BBFront) {
2713 --BBI;
2714 // If we found a call to a function, we can't assume it will return, so
2715 // information from below it cannot be propagated above it.
2716 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2717 break;
2718
2719 // Replace uses of the select or its condition with the known values.
2720 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2721 I != E; ++I) {
2722 if (*I == SI) {
2723 *I = SI->getOperand(NonNullOperand);
2724 AddToWorkList(BBI);
2725 } else if (*I == SelectCond) {
2726 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2727 ConstantInt::getFalse();
2728 AddToWorkList(BBI);
2729 }
2730 }
2731
2732 // If we past the instruction, quit looking for it.
2733 if (&*BBI == SI)
2734 SI = 0;
2735 if (&*BBI == SelectCond)
2736 SelectCond = 0;
2737
2738 // If we ran out of things to eliminate, break out of the loop.
2739 if (SelectCond == 0 && SI == 0)
2740 break;
2741
2742 }
2743 return true;
2744}
2745
2746
Reid Spencer1628cec2006-10-26 06:15:43 +00002747/// This function implements the transforms on div instructions that work
2748/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2749/// used by the visitors to those instructions.
2750/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002751Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002752 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002753
Chris Lattner50b2ca42008-02-19 06:12:18 +00002754 // undef / X -> 0 for integer.
2755 // undef / X -> undef for FP (the undef could be a snan).
2756 if (isa<UndefValue>(Op0)) {
2757 if (Op0->getType()->isFPOrFPVector())
2758 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002759 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002760 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002761
2762 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002763 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002764 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002765
Reid Spencer1628cec2006-10-26 06:15:43 +00002766 return 0;
2767}
Misha Brukmanfd939082005-04-21 23:48:37 +00002768
Reid Spencer1628cec2006-10-26 06:15:43 +00002769/// This function implements the transforms common to both integer division
2770/// instructions (udiv and sdiv). It is called by the visitors to those integer
2771/// division instructions.
2772/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002773Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2775
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002776 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002777 if (Op0 == Op1) {
2778 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2779 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2780 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2781 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2782 }
2783
2784 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2785 return ReplaceInstUsesWith(I, CI);
2786 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002787
Reid Spencer1628cec2006-10-26 06:15:43 +00002788 if (Instruction *Common = commonDivTransforms(I))
2789 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002790
2791 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2792 // This does not apply for fdiv.
2793 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2794 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002795
2796 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2797 // div X, 1 == X
2798 if (RHS->equalsInt(1))
2799 return ReplaceInstUsesWith(I, Op0);
2800
2801 // (X / C1) / C2 -> X / (C1*C2)
2802 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2803 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2804 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002805 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2806 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2807 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002808 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002809 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002810 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002811
Reid Spencerbca0e382007-03-23 20:05:17 +00002812 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2815 return R;
2816 if (isa<PHINode>(Op0))
2817 if (Instruction *NV = FoldOpIntoPhi(I))
2818 return NV;
2819 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002820 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002821
Chris Lattnera2881962003-02-18 19:28:33 +00002822 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002823 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002824 if (LHS->equalsInt(0))
2825 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2826
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002827 // It can't be division by zero, hence it must be division by one.
2828 if (I.getType() == Type::Int1Ty)
2829 return ReplaceInstUsesWith(I, Op0);
2830
Nick Lewycky895f0852008-11-27 20:21:08 +00002831 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2832 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2833 // div X, 1 == X
2834 if (X->isOne())
2835 return ReplaceInstUsesWith(I, Op0);
2836 }
2837
Reid Spencer1628cec2006-10-26 06:15:43 +00002838 return 0;
2839}
2840
2841Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2842 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2843
2844 // Handle the integer div common cases
2845 if (Instruction *Common = commonIDivTransforms(I))
2846 return Common;
2847
Reid Spencer1628cec2006-10-26 06:15:43 +00002848 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002849 // X udiv C^2 -> X >> C
2850 // Check to see if this is an unsigned division with an exact power of 2,
2851 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002852 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002853 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002854 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002855
2856 // X udiv C, where C >= signbit
2857 if (C->getValue().isNegative()) {
2858 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2859 I);
2860 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2861 ConstantInt::get(I.getType(), 1));
2862 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002863 }
2864
2865 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002866 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002867 if (RHSI->getOpcode() == Instruction::Shl &&
2868 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002869 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002870 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002871 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002872 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002873 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002874 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002875 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002876 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002877 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002878 }
2879 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002880 }
2881
Reid Spencer1628cec2006-10-26 06:15:43 +00002882 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2883 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002884 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002885 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002886 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002887 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002888 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002889 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002890 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002891 // Construct the "on true" case of the select
2892 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002893 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002894 Op0, TC, SI->getName()+".t");
2895 TSI = InsertNewInstBefore(TSI, I);
2896
2897 // Construct the "on false" case of the select
2898 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002899 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002900 Op0, FC, SI->getName()+".f");
2901 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002902
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002903 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002904 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002906 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002907 return 0;
2908}
2909
Reid Spencer1628cec2006-10-26 06:15:43 +00002910Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2911 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913 // Handle the integer div common cases
2914 if (Instruction *Common = commonIDivTransforms(I))
2915 return Common;
2916
2917 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2918 // sdiv X, -1 == -X
2919 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002920 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002921 }
2922
2923 // If the sign bits of both operands are zero (i.e. we can prove they are
2924 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002925 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002926 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002928 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002929 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002930 }
2931 }
2932
2933 return 0;
2934}
2935
2936Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2937 return commonDivTransforms(I);
2938}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002939
Reid Spencer0a783f72006-11-02 01:53:59 +00002940/// This function implements the transforms on rem instructions that work
2941/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2942/// is used by the visitors to those instructions.
2943/// @brief Transforms common to all three rem instructions
2944Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002946
Chris Lattner50b2ca42008-02-19 06:12:18 +00002947 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2948 if (I.getType()->isFPOrFPVector())
2949 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002951 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002952 if (isa<UndefValue>(Op1))
2953 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002954
2955 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002956 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2957 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002958
Reid Spencer0a783f72006-11-02 01:53:59 +00002959 return 0;
2960}
2961
2962/// This function implements the transforms common to both integer remainder
2963/// instructions (urem and srem). It is called by the visitors to those integer
2964/// remainder instructions.
2965/// @brief Common integer remainder transforms
2966Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2968
2969 if (Instruction *common = commonRemTransforms(I))
2970 return common;
2971
Dale Johannesened6af242009-01-21 00:35:19 +00002972 // 0 % X == 0 for integer, we don't need to preserve faults!
2973 if (Constant *LHS = dyn_cast<Constant>(Op0))
2974 if (LHS->isNullValue())
2975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2976
Chris Lattner857e8cd2004-12-12 21:48:58 +00002977 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002978 // X % 0 == undef, we don't need to preserve faults!
2979 if (RHS->equalsInt(0))
2980 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2981
Chris Lattnera2881962003-02-18 19:28:33 +00002982 if (RHS->equalsInt(1)) // X % 1 == 0
2983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984
Chris Lattner97943922006-02-28 05:49:21 +00002985 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2986 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2988 return R;
2989 } else if (isa<PHINode>(Op0I)) {
2990 if (Instruction *NV = FoldOpIntoPhi(I))
2991 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002992 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002993
2994 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00002995 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002996 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002997 }
Chris Lattnera2881962003-02-18 19:28:33 +00002998 }
2999
Reid Spencer0a783f72006-11-02 01:53:59 +00003000 return 0;
3001}
3002
3003Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3005
3006 if (Instruction *common = commonIRemTransforms(I))
3007 return common;
3008
3009 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3010 // X urem C^2 -> X and C
3011 // Check to see if this is an unsigned remainder with an exact power of 2,
3012 // if so, convert to a bitwise and.
3013 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003014 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003015 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003016 }
3017
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003018 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003019 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3020 if (RHSI->getOpcode() == Instruction::Shl &&
3021 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003022 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003023 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003024 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003025 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003026 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003027 }
3028 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003029 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003030
Reid Spencer0a783f72006-11-02 01:53:59 +00003031 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3032 // where C1&C2 are powers of two.
3033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3034 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3035 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3036 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003037 if ((STO->getValue().isPowerOf2()) &&
3038 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003039 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003041 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003042 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003043 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003044 }
3045 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003046 }
3047
Chris Lattner3f5b8772002-05-06 16:14:14 +00003048 return 0;
3049}
3050
Reid Spencer0a783f72006-11-02 01:53:59 +00003051Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
Dan Gohmancff55092007-11-05 23:16:33 +00003054 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003055 if (Instruction *common = commonIRemTransforms(I))
3056 return common;
3057
3058 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003059 if (!isa<Constant>(RHSNeg) ||
3060 (isa<ConstantInt>(RHSNeg) &&
3061 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003062 // X % -Y -> X % Y
3063 AddUsesToWorkList(I);
3064 I.setOperand(1, RHSNeg);
3065 return &I;
3066 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003067
Dan Gohmancff55092007-11-05 23:16:33 +00003068 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003069 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003070 if (I.getType()->isInteger()) {
3071 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3072 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3073 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003074 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003075 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003076 }
3077
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003078 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003079 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3080 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003081
Nick Lewycky9dce8732008-12-20 16:48:00 +00003082 bool hasNegative = false;
3083 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3084 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3085 if (RHS->getValue().isNegative())
3086 hasNegative = true;
3087
3088 if (hasNegative) {
3089 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003090 for (unsigned i = 0; i != VWidth; ++i) {
3091 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3092 if (RHS->getValue().isNegative())
3093 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3094 else
3095 Elts[i] = RHS;
3096 }
3097 }
3098
3099 Constant *NewRHSV = ConstantVector::get(Elts);
3100 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003101 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003102 I.setOperand(1, NewRHSV);
3103 return &I;
3104 }
3105 }
3106 }
3107
Reid Spencer0a783f72006-11-02 01:53:59 +00003108 return 0;
3109}
3110
3111Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003112 return commonRemTransforms(I);
3113}
3114
Chris Lattner457dd822004-06-09 07:59:58 +00003115// isOneBitSet - Return true if there is exactly one bit set in the specified
3116// constant.
3117static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003118 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003119}
3120
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003121// isHighOnes - Return true if the constant is of the form 1+0+.
3122// This is the same as lowones(~X).
3123static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003124 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003125}
3126
Reid Spencere4d87aa2006-12-23 06:05:41 +00003127/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003128/// are carefully arranged to allow folding of expressions such as:
3129///
3130/// (A < B) | (A > B) --> (A != B)
3131///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003132/// Note that this is only valid if the first and second predicates have the
3133/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003134///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003135/// Three bits are used to represent the condition, as follows:
3136/// 0 A > B
3137/// 1 A == B
3138/// 2 A < B
3139///
3140/// <=> Value Definition
3141/// 000 0 Always false
3142/// 001 1 A > B
3143/// 010 2 A == B
3144/// 011 3 A >= B
3145/// 100 4 A < B
3146/// 101 5 A != B
3147/// 110 6 A <= B
3148/// 111 7 Always true
3149///
3150static unsigned getICmpCode(const ICmpInst *ICI) {
3151 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003152 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003153 case ICmpInst::ICMP_UGT: return 1; // 001
3154 case ICmpInst::ICMP_SGT: return 1; // 001
3155 case ICmpInst::ICMP_EQ: return 2; // 010
3156 case ICmpInst::ICMP_UGE: return 3; // 011
3157 case ICmpInst::ICMP_SGE: return 3; // 011
3158 case ICmpInst::ICMP_ULT: return 4; // 100
3159 case ICmpInst::ICMP_SLT: return 4; // 100
3160 case ICmpInst::ICMP_NE: return 5; // 101
3161 case ICmpInst::ICMP_ULE: return 6; // 110
3162 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003163 // True -> 7
3164 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003165 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003166 return 0;
3167 }
3168}
3169
Evan Cheng8db90722008-10-14 17:15:11 +00003170/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3171/// predicate into a three bit mask. It also returns whether it is an ordered
3172/// predicate by reference.
3173static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3174 isOrdered = false;
3175 switch (CC) {
3176 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3177 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003178 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3179 case FCmpInst::FCMP_UGT: return 1; // 001
3180 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3181 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003182 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3183 case FCmpInst::FCMP_UGE: return 3; // 011
3184 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3185 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003186 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3187 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003188 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3189 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003190 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003191 default:
3192 // Not expecting FCMP_FALSE and FCMP_TRUE;
3193 assert(0 && "Unexpected FCmp predicate!");
3194 return 0;
3195 }
3196}
3197
Reid Spencere4d87aa2006-12-23 06:05:41 +00003198/// getICmpValue - This is the complement of getICmpCode, which turns an
3199/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003200/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003201/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003202static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3203 switch (code) {
3204 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003205 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003206 case 1:
3207 if (sign)
3208 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3209 else
3210 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3211 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3212 case 3:
3213 if (sign)
3214 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3215 else
3216 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3217 case 4:
3218 if (sign)
3219 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3220 else
3221 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3222 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3223 case 6:
3224 if (sign)
3225 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3226 else
3227 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003228 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003229 }
3230}
3231
Evan Cheng8db90722008-10-14 17:15:11 +00003232/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3233/// opcode and two operands into either a FCmp instruction. isordered is passed
3234/// in to determine which kind of predicate to use in the new fcmp instruction.
3235static Value *getFCmpValue(bool isordered, unsigned code,
3236 Value *LHS, Value *RHS) {
3237 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003238 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003239 case 0:
3240 if (isordered)
3241 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3242 else
3243 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3244 case 1:
3245 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003246 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3247 else
3248 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003249 case 2:
3250 if (isordered)
3251 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3252 else
3253 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003254 case 3:
3255 if (isordered)
3256 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3257 else
3258 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3259 case 4:
3260 if (isordered)
3261 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3262 else
3263 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3264 case 5:
3265 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003266 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3267 else
3268 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3269 case 6:
3270 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003271 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3272 else
3273 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003274 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003275 }
3276}
3277
Chris Lattnerb9553d62008-11-16 04:55:20 +00003278/// PredicatesFoldable - Return true if both predicates match sign or if at
3279/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003280static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3281 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003282 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3283 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284}
3285
3286namespace {
3287// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3288struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003289 InstCombiner &IC;
3290 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003291 ICmpInst::Predicate pred;
3292 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3293 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3294 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003295 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003296 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3297 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003298 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3299 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003300 return false;
3301 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302 Instruction *apply(Instruction &Log) const {
3303 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3304 if (ICI->getOperand(0) != LHS) {
3305 assert(ICI->getOperand(1) == LHS);
3306 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003307 }
3308
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003309 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003311 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003312 unsigned Code;
3313 switch (Log.getOpcode()) {
3314 case Instruction::And: Code = LHSCode & RHSCode; break;
3315 case Instruction::Or: Code = LHSCode | RHSCode; break;
3316 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003317 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003318 }
3319
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003320 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3321 ICmpInst::isSignedPredicate(ICI->getPredicate());
3322
3323 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003324 if (Instruction *I = dyn_cast<Instruction>(RV))
3325 return I;
3326 // Otherwise, it's a constant boolean value...
3327 return IC.ReplaceInstUsesWith(Log, RV);
3328 }
3329};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003330} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003331
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003332// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3333// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003334// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003335Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003336 ConstantInt *OpRHS,
3337 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003338 BinaryOperator &TheAnd) {
3339 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003340 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003341 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003342 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003343
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003344 switch (Op->getOpcode()) {
3345 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003346 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003347 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003348 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003349 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003350 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003351 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003352 }
3353 break;
3354 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003355 if (Together == AndRHS) // (X | C) & C --> C
3356 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003357
Chris Lattner6e7ba452005-01-01 16:22:27 +00003358 if (Op->hasOneUse() && Together != OpRHS) {
3359 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003360 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003361 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003362 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003363 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003364 }
3365 break;
3366 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003367 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003368 // Adding a one to a single bit bit-field should be turned into an XOR
3369 // of the bit. First thing to check is to see if this AND is with a
3370 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003371 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003372
3373 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003374 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003375 // Ok, at this point, we know that we are masking the result of the
3376 // ADD down to exactly one bit. If the constant we are adding has
3377 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003378 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003379
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003380 // Check to see if any bits below the one bit set in AndRHSV are set.
3381 if ((AddRHS & (AndRHSV-1)) == 0) {
3382 // If not, the only thing that can effect the output of the AND is
3383 // the bit specified by AndRHSV. If that bit is set, the effect of
3384 // the XOR is to toggle the bit. If it is clear, then the ADD has
3385 // no effect.
3386 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3387 TheAnd.setOperand(0, X);
3388 return &TheAnd;
3389 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003390 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003391 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003392 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003393 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003394 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003395 }
3396 }
3397 }
3398 }
3399 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003400
3401 case Instruction::Shl: {
3402 // We know that the AND will not produce any of the bits shifted in, so if
3403 // the anded constant includes them, clear them now!
3404 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003405 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003406 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003407 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3408 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003409
Zhou Sheng290bec52007-03-29 08:15:12 +00003410 if (CI->getValue() == ShlMask) {
3411 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003412 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3413 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003414 TheAnd.setOperand(1, CI);
3415 return &TheAnd;
3416 }
3417 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003418 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003419 case Instruction::LShr:
3420 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003421 // We know that the AND will not produce any of the bits shifted in, so if
3422 // the anded constant includes them, clear them now! This only applies to
3423 // unsigned shifts, because a signed shr may bring in set bits!
3424 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003425 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003426 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003427 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3428 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003429
Zhou Sheng290bec52007-03-29 08:15:12 +00003430 if (CI->getValue() == ShrMask) {
3431 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003432 return ReplaceInstUsesWith(TheAnd, Op);
3433 } else if (CI != AndRHS) {
3434 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3435 return &TheAnd;
3436 }
3437 break;
3438 }
3439 case Instruction::AShr:
3440 // Signed shr.
3441 // See if this is shifting in some sign extension, then masking it out
3442 // with an and.
3443 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003444 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003445 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003446 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3447 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003448 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003449 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003450 // Make the argument unsigned.
3451 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003452 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003453 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003454 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003455 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003456 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003457 }
3458 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003459 }
3460 return 0;
3461}
3462
Chris Lattner8b170942002-08-09 23:47:40 +00003463
Chris Lattnera96879a2004-09-29 17:40:11 +00003464/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3465/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3467/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003468/// insert new instructions.
3469Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003470 bool isSigned, bool Inside,
3471 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003472 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003473 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003474 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475
Chris Lattnera96879a2004-09-29 17:40:11 +00003476 if (Inside) {
3477 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003479
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003481 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003482 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3484 return new ICmpInst(pred, V, Hi);
3485 }
3486
3487 // Emit V-Lo <u Hi-Lo
3488 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003489 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003490 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003491 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3492 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003493 }
3494
3495 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003496 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003497
Reid Spencere4e40032007-03-21 23:19:50 +00003498 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003499 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003500 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 ICmpInst::Predicate pred = (isSigned ?
3502 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3503 return new ICmpInst(pred, V, Hi);
3504 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003505
Reid Spencere4e40032007-03-21 23:19:50 +00003506 // Emit V-Lo >u Hi-1-Lo
3507 // Note that Hi has already had one subtracted from it, above.
3508 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003509 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003510 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003511 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3512 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003513}
3514
Chris Lattner7203e152005-09-18 07:22:02 +00003515// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3516// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3517// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3518// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003519static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003520 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003521 uint32_t BitWidth = Val->getType()->getBitWidth();
3522 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003523
3524 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003525 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003526 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003527 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003528 return true;
3529}
3530
Chris Lattner7203e152005-09-18 07:22:02 +00003531/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3532/// where isSub determines whether the operator is a sub. If we can fold one of
3533/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003534///
3535/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3536/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3537/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3538///
3539/// return (A +/- B).
3540///
3541Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003542 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003543 Instruction &I) {
3544 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3545 if (!LHSI || LHSI->getNumOperands() != 2 ||
3546 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3547
3548 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3549
3550 switch (LHSI->getOpcode()) {
3551 default: return 0;
3552 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003553 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003554 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003555 if ((Mask->getValue().countLeadingZeros() +
3556 Mask->getValue().countPopulation()) ==
3557 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003558 break;
3559
3560 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3561 // part, we don't need any explicit masks to take them out of A. If that
3562 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003563 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003564 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003565 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003566 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003567 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003568 break;
3569 }
3570 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003571 return 0;
3572 case Instruction::Or:
3573 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003574 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003575 if ((Mask->getValue().countLeadingZeros() +
3576 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003577 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003578 break;
3579 return 0;
3580 }
3581
3582 Instruction *New;
3583 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003584 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003585 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003586 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003587 return InsertNewInstBefore(New, I);
3588}
3589
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003590/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3591Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3592 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003593 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003594 ConstantInt *LHSCst, *RHSCst;
3595 ICmpInst::Predicate LHSCC, RHSCC;
3596
Chris Lattnerea065fb2008-11-16 05:10:52 +00003597 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003598 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003599 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003600 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003601
3602 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3603 // where C is a power of 2
3604 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3605 LHSCst->getValue().isPowerOf2()) {
3606 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3607 InsertNewInstBefore(NewOr, I);
3608 return new ICmpInst(LHSCC, NewOr, LHSCst);
3609 }
3610
3611 // From here on, we only handle:
3612 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3613 if (Val != Val2) return 0;
3614
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003615 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3616 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3617 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3618 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3619 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3620 return 0;
3621
3622 // We can't fold (ugt x, C) & (sgt x, C2).
3623 if (!PredicatesFoldable(LHSCC, RHSCC))
3624 return 0;
3625
3626 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003627 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003628 if (ICmpInst::isSignedPredicate(LHSCC) ||
3629 (ICmpInst::isEquality(LHSCC) &&
3630 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003631 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003632 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003633 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3634
3635 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003636 std::swap(LHS, RHS);
3637 std::swap(LHSCst, RHSCst);
3638 std::swap(LHSCC, RHSCC);
3639 }
3640
3641 // At this point, we know we have have two icmp instructions
3642 // comparing a value against two constants and and'ing the result
3643 // together. Because of the above check, we know that we only have
3644 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3645 // (from the FoldICmpLogical check above), that the two constants
3646 // are not equal and that the larger constant is on the RHS
3647 assert(LHSCst != RHSCst && "Compares not folded above?");
3648
3649 switch (LHSCC) {
3650 default: assert(0 && "Unknown integer condition code!");
3651 case ICmpInst::ICMP_EQ:
3652 switch (RHSCC) {
3653 default: assert(0 && "Unknown integer condition code!");
3654 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3655 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3656 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3657 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3658 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3659 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3660 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3661 return ReplaceInstUsesWith(I, LHS);
3662 }
3663 case ICmpInst::ICMP_NE:
3664 switch (RHSCC) {
3665 default: assert(0 && "Unknown integer condition code!");
3666 case ICmpInst::ICMP_ULT:
3667 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3668 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3669 break; // (X != 13 & X u< 15) -> no change
3670 case ICmpInst::ICMP_SLT:
3671 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3672 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3673 break; // (X != 13 & X s< 15) -> no change
3674 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3675 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3676 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3677 return ReplaceInstUsesWith(I, RHS);
3678 case ICmpInst::ICMP_NE:
3679 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3680 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3681 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3682 Val->getName()+".off");
3683 InsertNewInstBefore(Add, I);
3684 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3685 ConstantInt::get(Add->getType(), 1));
3686 }
3687 break; // (X != 13 & X != 15) -> no change
3688 }
3689 break;
3690 case ICmpInst::ICMP_ULT:
3691 switch (RHSCC) {
3692 default: assert(0 && "Unknown integer condition code!");
3693 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3694 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3696 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3697 break;
3698 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3699 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3700 return ReplaceInstUsesWith(I, LHS);
3701 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3702 break;
3703 }
3704 break;
3705 case ICmpInst::ICMP_SLT:
3706 switch (RHSCC) {
3707 default: assert(0 && "Unknown integer condition code!");
3708 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3709 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3710 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3711 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3712 break;
3713 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3714 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3715 return ReplaceInstUsesWith(I, LHS);
3716 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3717 break;
3718 }
3719 break;
3720 case ICmpInst::ICMP_UGT:
3721 switch (RHSCC) {
3722 default: assert(0 && "Unknown integer condition code!");
3723 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3724 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3725 return ReplaceInstUsesWith(I, RHS);
3726 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3727 break;
3728 case ICmpInst::ICMP_NE:
3729 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3730 return new ICmpInst(LHSCC, Val, RHSCst);
3731 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003732 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003733 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3734 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3735 break;
3736 }
3737 break;
3738 case ICmpInst::ICMP_SGT:
3739 switch (RHSCC) {
3740 default: assert(0 && "Unknown integer condition code!");
3741 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3742 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3743 return ReplaceInstUsesWith(I, RHS);
3744 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3745 break;
3746 case ICmpInst::ICMP_NE:
3747 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3748 return new ICmpInst(LHSCC, Val, RHSCst);
3749 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003750 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003751 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3752 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3753 break;
3754 }
3755 break;
3756 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003757
3758 return 0;
3759}
3760
3761
Chris Lattner7e708292002-06-25 16:13:24 +00003762Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003763 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003765
Chris Lattnere87597f2004-10-16 18:11:37 +00003766 if (isa<UndefValue>(Op1)) // X & undef -> 0
3767 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3768
Chris Lattner6e7ba452005-01-01 16:22:27 +00003769 // and X, X = X
3770 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003771 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003772
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003773 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003774 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003775 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003776 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003777 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003778 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003779 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003780 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003781 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003782 } else if (isa<ConstantAggregateZero>(Op1)) {
3783 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003784 }
3785 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003786
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003787 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003788 const APInt& AndRHSMask = AndRHS->getValue();
3789 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003790
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003791 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003792 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003793 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003794 Value *Op0LHS = Op0I->getOperand(0);
3795 Value *Op0RHS = Op0I->getOperand(1);
3796 switch (Op0I->getOpcode()) {
3797 case Instruction::Xor:
3798 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003799 // If the mask is only needed on one incoming arm, push it up.
3800 if (Op0I->hasOneUse()) {
3801 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3802 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003803 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003804 Op0RHS->getName()+".masked");
3805 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003806 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003807 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003808 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003809 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003810 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3811 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003812 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003813 Op0LHS->getName()+".masked");
3814 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003815 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003816 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3817 }
3818 }
3819
Chris Lattner6e7ba452005-01-01 16:22:27 +00003820 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003821 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003822 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3823 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3824 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3825 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003826 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003827 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003828 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003829 break;
3830
3831 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003832 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3833 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3834 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3835 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003836 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003837
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003838 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3839 // has 1's for all bits that the subtraction with A might affect.
3840 if (Op0I->hasOneUse()) {
3841 uint32_t BitWidth = AndRHSMask.getBitWidth();
3842 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3843 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3844
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003845 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003846 if (!(A && A->isZero()) && // avoid infinite recursion.
3847 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003848 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3849 InsertNewInstBefore(NewNeg, I);
3850 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3851 }
3852 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003853 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003854
3855 case Instruction::Shl:
3856 case Instruction::LShr:
3857 // (1 << x) & 1 --> zext(x == 0)
3858 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003859 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003860 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3861 Constant::getNullValue(I.getType()));
3862 InsertNewInstBefore(NewICmp, I);
3863 return new ZExtInst(NewICmp, I.getType());
3864 }
3865 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003866 }
3867
Chris Lattner58403262003-07-23 19:25:52 +00003868 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003869 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003870 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003871 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003872 // If this is an integer truncation or change from signed-to-unsigned, and
3873 // if the source is an and/or with immediate, transform it. This
3874 // frequently occurs for bitfield accesses.
3875 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003876 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003877 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003878 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003879 if (CastOp->getOpcode() == Instruction::And) {
3880 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003881 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3882 // This will fold the two constants together, which may allow
3883 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003884 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003885 CastOp->getOperand(0), I.getType(),
3886 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003887 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003888 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003889 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003890 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003891 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003892 } else if (CastOp->getOpcode() == Instruction::Or) {
3893 // Change: and (cast (or X, C1) to T), C2
3894 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003895 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003896 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3897 return ReplaceInstUsesWith(I, AndRHS);
3898 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003899 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003900 }
Chris Lattner06782f82003-07-23 19:36:21 +00003901 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003902
3903 // Try to fold constant and into select arguments.
3904 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003905 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003906 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003907 if (isa<PHINode>(Op0))
3908 if (Instruction *NV = FoldOpIntoPhi(I))
3909 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003910 }
3911
Chris Lattner8d969642003-03-10 23:06:50 +00003912 Value *Op0NotVal = dyn_castNotVal(Op0);
3913 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003914
Chris Lattner5b62aa72004-06-18 06:07:51 +00003915 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3917
Misha Brukmancb6267b2004-07-30 12:50:08 +00003918 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003919 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003920 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003921 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003922 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003923 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003924 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003925
3926 {
Chris Lattner003b6202007-06-15 05:58:24 +00003927 Value *A = 0, *B = 0, *C = 0, *D = 0;
3928 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003929 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3930 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003931
3932 // (A|B) & ~(A&B) -> A^B
3933 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3934 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003935 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003936 }
3937 }
3938
3939 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003940 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3941 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003942
3943 // ~(A&B) & (A|B) -> A^B
3944 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3945 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003947 }
3948 }
Chris Lattner64daab52006-04-01 08:03:55 +00003949
3950 if (Op0->hasOneUse() &&
3951 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3952 if (A == Op1) { // (A^B)&A -> A&(A^B)
3953 I.swapOperands(); // Simplify below
3954 std::swap(Op0, Op1);
3955 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3956 cast<BinaryOperator>(Op0)->swapOperands();
3957 I.swapOperands(); // Simplify below
3958 std::swap(Op0, Op1);
3959 }
3960 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003961
Chris Lattner64daab52006-04-01 08:03:55 +00003962 if (Op1->hasOneUse() &&
3963 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3964 if (B == Op0) { // B&(A^B) -> B&(B^A)
3965 cast<BinaryOperator>(Op1)->swapOperands();
3966 std::swap(A, B);
3967 }
3968 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003969 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003970 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003971 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003972 }
3973 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003974
3975 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00003976 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3977 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3978 return BinaryOperator::CreateAnd(A, Op1);
3979 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3980 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3981 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00003982 }
3983
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3985 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3986 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003987 return R;
3988
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003989 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3990 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3991 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00003992 }
3993
Chris Lattner6fc205f2006-05-05 06:39:07 +00003994 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003995 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3996 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3997 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3998 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003999 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004000 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4002 I.getType(), TD) &&
4003 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4004 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004005 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004006 Op1C->getOperand(0),
4007 I.getName());
4008 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004009 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004010 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004011 }
Chris Lattnere511b742006-11-14 07:46:50 +00004012
4013 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004014 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4015 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4016 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004017 SI0->getOperand(1) == SI1->getOperand(1) &&
4018 (SI0->hasOneUse() || SI1->hasOneUse())) {
4019 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004021 SI1->getOperand(0),
4022 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004023 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004024 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004025 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004026 }
4027
Evan Cheng8db90722008-10-14 17:15:11 +00004028 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004029 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4030 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4031 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004032 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4033 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004034 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4035 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4036 // If either of the constants are nans, then the whole thing returns
4037 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004038 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004039 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4040 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4041 RHS->getOperand(0));
4042 }
Evan Cheng8db90722008-10-14 17:15:11 +00004043 } else {
4044 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4045 FCmpInst::Predicate Op0CC, Op1CC;
4046 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4047 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004048 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4049 // Swap RHS operands to match LHS.
4050 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4051 std::swap(Op1LHS, Op1RHS);
4052 }
Evan Cheng8db90722008-10-14 17:15:11 +00004053 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4054 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4055 if (Op0CC == Op1CC)
4056 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4057 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4058 Op1CC == FCmpInst::FCMP_FALSE)
4059 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4060 else if (Op0CC == FCmpInst::FCMP_TRUE)
4061 return ReplaceInstUsesWith(I, Op1);
4062 else if (Op1CC == FCmpInst::FCMP_TRUE)
4063 return ReplaceInstUsesWith(I, Op0);
4064 bool Op0Ordered;
4065 bool Op1Ordered;
4066 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4067 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4068 if (Op1Pred == 0) {
4069 std::swap(Op0, Op1);
4070 std::swap(Op0Pred, Op1Pred);
4071 std::swap(Op0Ordered, Op1Ordered);
4072 }
4073 if (Op0Pred == 0) {
4074 // uno && ueq -> uno && (uno || eq) -> ueq
4075 // ord && olt -> ord && (ord && lt) -> olt
4076 if (Op0Ordered == Op1Ordered)
4077 return ReplaceInstUsesWith(I, Op1);
4078 // uno && oeq -> uno && (ord && eq) -> false
4079 // uno && ord -> false
4080 if (!Op0Ordered)
4081 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4082 // ord && ueq -> ord && (uno || eq) -> oeq
4083 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4084 Op0LHS, Op0RHS));
4085 }
4086 }
4087 }
4088 }
Chris Lattner99c65742007-10-24 05:38:08 +00004089 }
4090 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004091
Chris Lattner7e708292002-06-25 16:13:24 +00004092 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004093}
4094
Chris Lattner8c34cd22008-10-05 02:13:19 +00004095/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4096/// capable of providing pieces of a bswap. The subexpression provides pieces
4097/// of a bswap if it is proven that each of the non-zero bytes in the output of
4098/// the expression came from the corresponding "byte swapped" byte in some other
4099/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4100/// we know that the expression deposits the low byte of %X into the high byte
4101/// of the bswap result and that all other bytes are zero. This expression is
4102/// accepted, the high byte of ByteValues is set to X to indicate a correct
4103/// match.
4104///
4105/// This function returns true if the match was unsuccessful and false if so.
4106/// On entry to the function the "OverallLeftShift" is a signed integer value
4107/// indicating the number of bytes that the subexpression is later shifted. For
4108/// example, if the expression is later right shifted by 16 bits, the
4109/// OverallLeftShift value would be -2 on entry. This is used to specify which
4110/// byte of ByteValues is actually being set.
4111///
4112/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4113/// byte is masked to zero by a user. For example, in (X & 255), X will be
4114/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4115/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4116/// always in the local (OverallLeftShift) coordinate space.
4117///
4118static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4119 SmallVector<Value*, 8> &ByteValues) {
4120 if (Instruction *I = dyn_cast<Instruction>(V)) {
4121 // If this is an or instruction, it may be an inner node of the bswap.
4122 if (I->getOpcode() == Instruction::Or) {
4123 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4124 ByteValues) ||
4125 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4126 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004127 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004128
4129 // If this is a logical shift by a constant multiple of 8, recurse with
4130 // OverallLeftShift and ByteMask adjusted.
4131 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4132 unsigned ShAmt =
4133 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4134 // Ensure the shift amount is defined and of a byte value.
4135 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4136 return true;
4137
4138 unsigned ByteShift = ShAmt >> 3;
4139 if (I->getOpcode() == Instruction::Shl) {
4140 // X << 2 -> collect(X, +2)
4141 OverallLeftShift += ByteShift;
4142 ByteMask >>= ByteShift;
4143 } else {
4144 // X >>u 2 -> collect(X, -2)
4145 OverallLeftShift -= ByteShift;
4146 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004147 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004148 }
4149
4150 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4151 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4152
4153 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4154 ByteValues);
4155 }
4156
4157 // If this is a logical 'and' with a mask that clears bytes, clear the
4158 // corresponding bytes in ByteMask.
4159 if (I->getOpcode() == Instruction::And &&
4160 isa<ConstantInt>(I->getOperand(1))) {
4161 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4162 unsigned NumBytes = ByteValues.size();
4163 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4164 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4165
4166 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4167 // If this byte is masked out by a later operation, we don't care what
4168 // the and mask is.
4169 if ((ByteMask & (1 << i)) == 0)
4170 continue;
4171
4172 // If the AndMask is all zeros for this byte, clear the bit.
4173 APInt MaskB = AndMask & Byte;
4174 if (MaskB == 0) {
4175 ByteMask &= ~(1U << i);
4176 continue;
4177 }
4178
4179 // If the AndMask is not all ones for this byte, it's not a bytezap.
4180 if (MaskB != Byte)
4181 return true;
4182
4183 // Otherwise, this byte is kept.
4184 }
4185
4186 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4187 ByteValues);
4188 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004189 }
4190
Chris Lattner8c34cd22008-10-05 02:13:19 +00004191 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4192 // the input value to the bswap. Some observations: 1) if more than one byte
4193 // is demanded from this input, then it could not be successfully assembled
4194 // into a byteswap. At least one of the two bytes would not be aligned with
4195 // their ultimate destination.
4196 if (!isPowerOf2_32(ByteMask)) return true;
4197 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004198
Chris Lattner8c34cd22008-10-05 02:13:19 +00004199 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4200 // is demanded, it needs to go into byte 0 of the result. This means that the
4201 // byte needs to be shifted until it lands in the right byte bucket. The
4202 // shift amount depends on the position: if the byte is coming from the high
4203 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4204 // low part, it must be shifted left.
4205 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4206 if (InputByteNo < ByteValues.size()/2) {
4207 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4208 return true;
4209 } else {
4210 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4211 return true;
4212 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004213
4214 // If the destination byte value is already defined, the values are or'd
4215 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004216 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004217 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004218 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004219 return false;
4220}
4221
4222/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4223/// If so, insert the new bswap intrinsic and return it.
4224Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004225 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004226 if (!ITy || ITy->getBitWidth() % 16 ||
4227 // ByteMask only allows up to 32-byte values.
4228 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004229 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004230
4231 /// ByteValues - For each byte of the result, we keep track of which value
4232 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004233 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004234 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004235
4236 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004237 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4238 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004239 return 0;
4240
4241 // Check to see if all of the bytes come from the same value.
4242 Value *V = ByteValues[0];
4243 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4244
4245 // Check to make sure that all of the bytes come from the same value.
4246 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4247 if (ByteValues[i] != V)
4248 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004249 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004250 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004251 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004252 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004253}
4254
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004255/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4256/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4257/// we can simplify this expression to "cond ? C : D or B".
4258static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4259 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004260 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004261 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004262 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004263 return 0;
4264
Chris Lattnera6a474d2008-11-16 04:26:55 +00004265 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004266 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004267 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004268 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004269 return SelectInst::Create(Cond, C, B);
4270 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004271 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004272 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004273 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004274 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004275 return 0;
4276}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004277
Chris Lattner69d4ced2008-11-16 05:20:07 +00004278/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4279Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4280 ICmpInst *LHS, ICmpInst *RHS) {
4281 Value *Val, *Val2;
4282 ConstantInt *LHSCst, *RHSCst;
4283 ICmpInst::Predicate LHSCC, RHSCC;
4284
4285 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4286 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4287 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4288 return 0;
4289
4290 // From here on, we only handle:
4291 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4292 if (Val != Val2) return 0;
4293
4294 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4295 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4296 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4297 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4298 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4299 return 0;
4300
4301 // We can't fold (ugt x, C) | (sgt x, C2).
4302 if (!PredicatesFoldable(LHSCC, RHSCC))
4303 return 0;
4304
4305 // Ensure that the larger constant is on the RHS.
4306 bool ShouldSwap;
4307 if (ICmpInst::isSignedPredicate(LHSCC) ||
4308 (ICmpInst::isEquality(LHSCC) &&
4309 ICmpInst::isSignedPredicate(RHSCC)))
4310 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4311 else
4312 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4313
4314 if (ShouldSwap) {
4315 std::swap(LHS, RHS);
4316 std::swap(LHSCst, RHSCst);
4317 std::swap(LHSCC, RHSCC);
4318 }
4319
4320 // At this point, we know we have have two icmp instructions
4321 // comparing a value against two constants and or'ing the result
4322 // together. Because of the above check, we know that we only have
4323 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4324 // FoldICmpLogical check above), that the two constants are not
4325 // equal.
4326 assert(LHSCst != RHSCst && "Compares not folded above?");
4327
4328 switch (LHSCC) {
4329 default: assert(0 && "Unknown integer condition code!");
4330 case ICmpInst::ICMP_EQ:
4331 switch (RHSCC) {
4332 default: assert(0 && "Unknown integer condition code!");
4333 case ICmpInst::ICMP_EQ:
4334 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4335 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4336 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4337 Val->getName()+".off");
4338 InsertNewInstBefore(Add, I);
4339 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4340 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4341 }
4342 break; // (X == 13 | X == 15) -> no change
4343 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4344 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4345 break;
4346 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4347 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4348 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4349 return ReplaceInstUsesWith(I, RHS);
4350 }
4351 break;
4352 case ICmpInst::ICMP_NE:
4353 switch (RHSCC) {
4354 default: assert(0 && "Unknown integer condition code!");
4355 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4356 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4357 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4358 return ReplaceInstUsesWith(I, LHS);
4359 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4360 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4361 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4362 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4363 }
4364 break;
4365 case ICmpInst::ICMP_ULT:
4366 switch (RHSCC) {
4367 default: assert(0 && "Unknown integer condition code!");
4368 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4369 break;
4370 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4371 // If RHSCst is [us]MAXINT, it is always false. Not handling
4372 // this can cause overflow.
4373 if (RHSCst->isMaxValue(false))
4374 return ReplaceInstUsesWith(I, LHS);
4375 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4376 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4377 break;
4378 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4379 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4380 return ReplaceInstUsesWith(I, RHS);
4381 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4382 break;
4383 }
4384 break;
4385 case ICmpInst::ICMP_SLT:
4386 switch (RHSCC) {
4387 default: assert(0 && "Unknown integer condition code!");
4388 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4389 break;
4390 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4391 // If RHSCst is [us]MAXINT, it is always false. Not handling
4392 // this can cause overflow.
4393 if (RHSCst->isMaxValue(true))
4394 return ReplaceInstUsesWith(I, LHS);
4395 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4396 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4397 break;
4398 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4399 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4400 return ReplaceInstUsesWith(I, RHS);
4401 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4402 break;
4403 }
4404 break;
4405 case ICmpInst::ICMP_UGT:
4406 switch (RHSCC) {
4407 default: assert(0 && "Unknown integer condition code!");
4408 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4409 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4410 return ReplaceInstUsesWith(I, LHS);
4411 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4412 break;
4413 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4414 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4415 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4416 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4417 break;
4418 }
4419 break;
4420 case ICmpInst::ICMP_SGT:
4421 switch (RHSCC) {
4422 default: assert(0 && "Unknown integer condition code!");
4423 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4424 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4425 return ReplaceInstUsesWith(I, LHS);
4426 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4427 break;
4428 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4429 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4430 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4431 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4432 break;
4433 }
4434 break;
4435 }
4436 return 0;
4437}
4438
Bill Wendlinga698a472008-12-01 08:23:25 +00004439/// FoldOrWithConstants - This helper function folds:
4440///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004441/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004442///
4443/// into:
4444///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004445/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004446///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004447/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004448Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004449 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004450 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4451 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004452
Bill Wendling286a0542008-12-02 06:24:20 +00004453 Value *V1 = 0;
4454 ConstantInt *CI2 = 0;
4455 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004456
Bill Wendling29976b92008-12-02 06:18:11 +00004457 APInt Xor = CI1->getValue() ^ CI2->getValue();
4458 if (!Xor.isAllOnesValue()) return 0;
4459
Bill Wendling286a0542008-12-02 06:24:20 +00004460 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004461 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004462 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4463 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004464 }
4465
4466 return 0;
4467}
4468
Chris Lattner7e708292002-06-25 16:13:24 +00004469Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004470 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004472
Chris Lattner42593e62007-03-24 23:56:43 +00004473 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004474 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004475
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004476 // or X, X = X
4477 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004478 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004479
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004480 // See if we can simplify any instructions used by the instruction whose sole
4481 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004482 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004483 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004484 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004485 } else if (isa<ConstantAggregateZero>(Op1)) {
4486 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4487 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4488 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4489 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004490 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004491
4492
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004493
Chris Lattner3f5b8772002-05-06 16:14:14 +00004494 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004495 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004496 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004497 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4498 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004499 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004500 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004501 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004502 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004503 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004504 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004505
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004506 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4507 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004508 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004509 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004510 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004511 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004512 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004513 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004514
4515 // Try to fold constant and into select arguments.
4516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004518 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004519 if (isa<PHINode>(Op0))
4520 if (Instruction *NV = FoldOpIntoPhi(I))
4521 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004522 }
4523
Chris Lattner4f637d42006-01-06 17:59:59 +00004524 Value *A = 0, *B = 0;
4525 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004526
4527 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4528 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4529 return ReplaceInstUsesWith(I, Op1);
4530 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4531 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4532 return ReplaceInstUsesWith(I, Op0);
4533
Chris Lattner6423d4c2006-07-10 20:25:24 +00004534 // (A | B) | C and A | (B | C) -> bswap if possible.
4535 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004536 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004537 match(Op1, m_Or(m_Value(), m_Value())) ||
4538 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4539 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004540 if (Instruction *BSwap = MatchBSwap(I))
4541 return BSwap;
4542 }
4543
Chris Lattner6e4c6492005-05-09 04:58:36 +00004544 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4545 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004546 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004547 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004548 InsertNewInstBefore(NOr, I);
4549 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004550 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004551 }
4552
4553 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4554 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004555 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004556 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004557 InsertNewInstBefore(NOr, I);
4558 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004559 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004560 }
4561
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004562 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004563 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004564 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4565 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004566 Value *V1 = 0, *V2 = 0, *V3 = 0;
4567 C1 = dyn_cast<ConstantInt>(C);
4568 C2 = dyn_cast<ConstantInt>(D);
4569 if (C1 && C2) { // (A & C1)|(B & C2)
4570 // If we have: ((V + N) & C1) | (V & C2)
4571 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4572 // replace with V+N.
4573 if (C1->getValue() == ~C2->getValue()) {
4574 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4575 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4576 // Add commutes, try both ways.
4577 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4578 return ReplaceInstUsesWith(I, A);
4579 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4580 return ReplaceInstUsesWith(I, A);
4581 }
4582 // Or commutes, try both ways.
4583 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4584 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4585 // Add commutes, try both ways.
4586 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4587 return ReplaceInstUsesWith(I, B);
4588 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4589 return ReplaceInstUsesWith(I, B);
4590 }
4591 }
Chris Lattner044e5332007-04-08 08:01:49 +00004592 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004593 }
4594
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004595 // Check to see if we have any common things being and'ed. If so, find the
4596 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004597 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4598 if (A == B) // (A & C)|(A & D) == A & (C|D)
4599 V1 = A, V2 = C, V3 = D;
4600 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4601 V1 = A, V2 = B, V3 = C;
4602 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4603 V1 = C, V2 = A, V3 = D;
4604 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4605 V1 = C, V2 = A, V3 = B;
4606
4607 if (V1) {
4608 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004609 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4610 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004611 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004612 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004613
Dan Gohman1975d032008-10-30 20:40:10 +00004614 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004615 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4616 return Match;
4617 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4618 return Match;
4619 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4620 return Match;
4621 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4622 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004623
Bill Wendlingb01865c2008-11-30 13:52:49 +00004624 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004625 if ((match(C, m_Not(m_Specific(D))) &&
4626 match(B, m_Not(m_Specific(A)))))
4627 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004628 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004629 if ((match(A, m_Not(m_Specific(D))) &&
4630 match(B, m_Not(m_Specific(C)))))
4631 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004632 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004633 if ((match(C, m_Not(m_Specific(B))) &&
4634 match(D, m_Not(m_Specific(A)))))
4635 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004636 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004637 if ((match(A, m_Not(m_Specific(B))) &&
4638 match(D, m_Not(m_Specific(C)))))
4639 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004640 }
Chris Lattnere511b742006-11-14 07:46:50 +00004641
4642 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004643 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4644 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4645 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004646 SI0->getOperand(1) == SI1->getOperand(1) &&
4647 (SI0->hasOneUse() || SI1->hasOneUse())) {
4648 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004649 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004650 SI1->getOperand(0),
4651 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004652 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004653 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004654 }
4655 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004656
Bill Wendlingb3833d12008-12-01 01:07:11 +00004657 // ((A|B)&1)|(B&-2) -> (A&1) | B
4658 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4659 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004660 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004661 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004662 }
4663 // (B&-2)|((A|B)&1) -> (A&1) | B
4664 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4665 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004666 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004667 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004668 }
4669
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004670 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4671 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004672 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004673 } else {
4674 A = 0;
4675 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004676 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004677 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4678 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004679 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004680
Misha Brukmancb6267b2004-07-30 12:50:08 +00004681 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004682 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004683 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004684 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004685 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004686 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004687 }
Chris Lattnera2881962003-02-18 19:28:33 +00004688
Reid Spencere4d87aa2006-12-23 06:05:41 +00004689 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4690 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4691 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004692 return R;
4693
Chris Lattner69d4ced2008-11-16 05:20:07 +00004694 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4695 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4696 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004697 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004698
4699 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004700 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004701 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004702 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004703 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4704 !isa<ICmpInst>(Op1C->getOperand(0))) {
4705 const Type *SrcTy = Op0C->getOperand(0)->getType();
4706 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4707 // Only do this if the casts both really cause code to be
4708 // generated.
4709 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4710 I.getType(), TD) &&
4711 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4712 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004713 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004714 Op1C->getOperand(0),
4715 I.getName());
4716 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004717 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004718 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004719 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004720 }
Chris Lattner99c65742007-10-24 05:38:08 +00004721 }
4722
4723
4724 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4725 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4726 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4727 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004728 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004729 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004730 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4731 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4732 // If either of the constants are nans, then the whole thing returns
4733 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004734 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004735 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4736
4737 // Otherwise, no need to compare the two constants, compare the
4738 // rest.
4739 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4740 RHS->getOperand(0));
4741 }
Evan Cheng40300622008-10-14 18:44:08 +00004742 } else {
4743 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4744 FCmpInst::Predicate Op0CC, Op1CC;
4745 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4746 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4747 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4748 // Swap RHS operands to match LHS.
4749 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4750 std::swap(Op1LHS, Op1RHS);
4751 }
4752 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4753 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4754 if (Op0CC == Op1CC)
4755 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4756 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4757 Op1CC == FCmpInst::FCMP_TRUE)
4758 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4759 else if (Op0CC == FCmpInst::FCMP_FALSE)
4760 return ReplaceInstUsesWith(I, Op1);
4761 else if (Op1CC == FCmpInst::FCMP_FALSE)
4762 return ReplaceInstUsesWith(I, Op0);
4763 bool Op0Ordered;
4764 bool Op1Ordered;
4765 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4766 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4767 if (Op0Ordered == Op1Ordered) {
4768 // If both are ordered or unordered, return a new fcmp with
4769 // or'ed predicates.
4770 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4771 Op0LHS, Op0RHS);
4772 if (Instruction *I = dyn_cast<Instruction>(RV))
4773 return I;
4774 // Otherwise, it's a constant boolean value...
4775 return ReplaceInstUsesWith(I, RV);
4776 }
4777 }
4778 }
4779 }
Chris Lattner99c65742007-10-24 05:38:08 +00004780 }
4781 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004782
Chris Lattner7e708292002-06-25 16:13:24 +00004783 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004784}
4785
Dan Gohman844731a2008-05-13 00:00:25 +00004786namespace {
4787
Chris Lattnerc317d392004-02-16 01:20:27 +00004788// XorSelf - Implements: X ^ X --> 0
4789struct XorSelf {
4790 Value *RHS;
4791 XorSelf(Value *rhs) : RHS(rhs) {}
4792 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4793 Instruction *apply(BinaryOperator &Xor) const {
4794 return &Xor;
4795 }
4796};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004797
Dan Gohman844731a2008-05-13 00:00:25 +00004798}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004799
Chris Lattner7e708292002-06-25 16:13:24 +00004800Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004801 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004802 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004803
Evan Chengd34af782008-03-25 20:07:13 +00004804 if (isa<UndefValue>(Op1)) {
4805 if (isa<UndefValue>(Op0))
4806 // Handle undef ^ undef -> 0 special case. This is a common
4807 // idiom (misuse).
4808 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004809 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004810 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004811
Chris Lattnerc317d392004-02-16 01:20:27 +00004812 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4813 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004814 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004815 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004816 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004817
4818 // See if we can simplify any instructions used by the instruction whose sole
4819 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004820 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004821 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004822 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004823 } else if (isa<ConstantAggregateZero>(Op1)) {
4824 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004825 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004826
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004827 // Is this a ~ operation?
4828 if (Value *NotOp = dyn_castNotVal(&I)) {
4829 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4830 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4831 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4832 if (Op0I->getOpcode() == Instruction::And ||
4833 Op0I->getOpcode() == Instruction::Or) {
4834 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4835 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4836 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004837 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004838 Op0I->getOperand(1)->getName()+".not");
4839 InsertNewInstBefore(NotY, I);
4840 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004841 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004842 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004843 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004844 }
4845 }
4846 }
4847 }
4848
4849
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004850 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004851 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004852 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004853 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004854 return new ICmpInst(ICI->getInversePredicate(),
4855 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004856
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004857 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4858 return new FCmpInst(FCI->getInversePredicate(),
4859 FCI->getOperand(0), FCI->getOperand(1));
4860 }
4861
Nick Lewycky517e1f52008-05-31 19:01:33 +00004862 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4863 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4864 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4865 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4866 Instruction::CastOps Opcode = Op0C->getOpcode();
4867 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4868 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4869 Op0C->getDestTy())) {
4870 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4871 CI->getOpcode(), CI->getInversePredicate(),
4872 CI->getOperand(0), CI->getOperand(1)), I);
4873 NewCI->takeName(CI);
4874 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4875 }
4876 }
4877 }
4878 }
4879 }
4880
Reid Spencere4d87aa2006-12-23 06:05:41 +00004881 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004882 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004883 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4884 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004885 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4886 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004887 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004888 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004889 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004890
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004891 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004892 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004893 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004894 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004895 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004896 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004897 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004898 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004899 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004900 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004901 // (X + C) ^ signbit -> (X + C + signbit)
4902 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004904
Chris Lattner7c4049c2004-01-12 19:35:11 +00004905 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004906 } else if (Op0I->getOpcode() == Instruction::Or) {
4907 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004908 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004909 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4910 // Anything in both C1 and C2 is known to be zero, remove it from
4911 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004912 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004913 NewRHS = ConstantExpr::getAnd(NewRHS,
4914 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004915 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004916 I.setOperand(0, Op0I->getOperand(0));
4917 I.setOperand(1, NewRHS);
4918 return &I;
4919 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004920 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004921 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004922 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004923
4924 // Try to fold constant and into select arguments.
4925 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004926 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004927 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004928 if (isa<PHINode>(Op0))
4929 if (Instruction *NV = FoldOpIntoPhi(I))
4930 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004931 }
4932
Chris Lattner8d969642003-03-10 23:06:50 +00004933 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004934 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004935 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004936
Chris Lattner8d969642003-03-10 23:06:50 +00004937 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004938 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004939 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004940
Chris Lattner318bf792007-03-18 22:51:34 +00004941
4942 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4943 if (Op1I) {
4944 Value *A, *B;
4945 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4946 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004947 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004948 I.swapOperands();
4949 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004950 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004951 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004952 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004953 }
Chris Lattnercb504b92008-11-16 05:38:51 +00004954 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4955 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4956 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4957 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00004958 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004959 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004960 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004961 std::swap(A, B);
4962 }
Chris Lattner318bf792007-03-18 22:51:34 +00004963 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004964 I.swapOperands(); // Simplified below.
4965 std::swap(Op0, Op1);
4966 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004967 }
Chris Lattner318bf792007-03-18 22:51:34 +00004968 }
4969
4970 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4971 if (Op0I) {
4972 Value *A, *B;
4973 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4974 if (A == Op1) // (B|A)^B == (A|B)^B
4975 std::swap(A, B);
4976 if (B == Op1) { // (A|B)^B == A & ~B
4977 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4979 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004980 }
Chris Lattnercb504b92008-11-16 05:38:51 +00004981 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4982 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
4983 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4984 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00004985 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4986 if (A == Op1) // (A&B)^A -> (B&A)^A
4987 std::swap(A, B);
4988 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004989 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004990 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004991 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4992 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004993 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004994 }
Chris Lattner318bf792007-03-18 22:51:34 +00004995 }
4996
4997 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4998 if (Op0I && Op1I && Op0I->isShift() &&
4999 Op0I->getOpcode() == Op1I->getOpcode() &&
5000 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5001 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5002 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005004 Op1I->getOperand(0),
5005 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005006 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005007 Op1I->getOperand(1));
5008 }
5009
5010 if (Op0I && Op1I) {
5011 Value *A, *B, *C, *D;
5012 // (A & B)^(A | B) -> A ^ B
5013 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5014 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5015 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005016 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005017 }
5018 // (A | B)^(A & B) -> A ^ B
5019 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5020 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5021 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005022 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005023 }
5024
5025 // (A & B)^(C & D)
5026 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5027 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5028 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5029 // (X & Y)^(X & Y) -> (Y^Z) & X
5030 Value *X = 0, *Y = 0, *Z = 0;
5031 if (A == C)
5032 X = A, Y = B, Z = D;
5033 else if (A == D)
5034 X = A, Y = B, Z = C;
5035 else if (B == C)
5036 X = B, Y = A, Z = D;
5037 else if (B == D)
5038 X = B, Y = A, Z = C;
5039
5040 if (X) {
5041 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005042 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5043 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005044 }
5045 }
5046 }
5047
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5049 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5050 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005051 return R;
5052
Chris Lattner6fc205f2006-05-05 06:39:07 +00005053 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005054 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005055 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005056 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5057 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005058 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005059 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5061 I.getType(), TD) &&
5062 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5063 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005065 Op1C->getOperand(0),
5066 I.getName());
5067 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005068 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005069 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005070 }
Chris Lattner99c65742007-10-24 05:38:08 +00005071 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005072
Chris Lattner7e708292002-06-25 16:13:24 +00005073 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005074}
5075
Chris Lattnera96879a2004-09-29 17:40:11 +00005076/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5077/// overflowed for this type.
5078static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005079 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005080 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005081
Reid Spencere4e40032007-03-21 23:19:50 +00005082 if (IsSigned)
5083 if (In2->getValue().isNegative())
5084 return Result->getValue().sgt(In1->getValue());
5085 else
5086 return Result->getValue().slt(In1->getValue());
5087 else
5088 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005089}
5090
Dan Gohman1df3fd62008-09-10 23:30:57 +00005091/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5092/// overflowed for this type.
5093static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5094 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005095 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005096
5097 if (IsSigned)
5098 if (In2->getValue().isNegative())
5099 return Result->getValue().slt(In1->getValue());
5100 else
5101 return Result->getValue().sgt(In1->getValue());
5102 else
5103 return Result->getValue().ugt(In1->getValue());
5104}
5105
Chris Lattner574da9b2005-01-13 20:14:25 +00005106/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5107/// code necessary to compute the offset from the base pointer (without adding
5108/// in the base pointer). Return the result as a signed integer of intptr size.
5109static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5110 TargetData &TD = IC.getTargetData();
5111 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 const Type *IntPtrTy = TD.getIntPtrType();
5113 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005114
5115 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005116 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005117 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005118
Gabor Greif177dd3f2008-06-12 21:37:33 +00005119 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5120 ++i, ++GTI) {
5121 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005122 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005123 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5124 if (OpC->isZero()) continue;
5125
5126 // Handle a struct index, which adds its field offset to the pointer.
5127 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5128 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5129
5130 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5131 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005132 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005133 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005134 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005135 ConstantInt::get(IntPtrTy, Size),
5136 GEP->getName()+".offs"), I);
5137 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005138 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005139
5140 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5141 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5142 Scale = ConstantExpr::getMul(OC, Scale);
5143 if (Constant *RC = dyn_cast<Constant>(Result))
5144 Result = ConstantExpr::getAdd(RC, Scale);
5145 else {
5146 // Emit an add instruction.
5147 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005148 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005149 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005150 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005151 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005152 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005153 // Convert to correct type.
5154 if (Op->getType() != IntPtrTy) {
5155 if (Constant *OpC = dyn_cast<Constant>(Op))
5156 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5157 else
5158 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5159 Op->getName()+".c"), I);
5160 }
5161 if (Size != 1) {
5162 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163 if (Constant *OpC = dyn_cast<Constant>(Op))
5164 Op = ConstantExpr::getMul(OpC, Scale);
5165 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005166 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005167 GEP->getName()+".idx"), I);
5168 }
5169
5170 // Emit an add instruction.
5171 if (isa<Constant>(Op) && isa<Constant>(Result))
5172 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5173 cast<Constant>(Result));
5174 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005175 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005176 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005177 }
5178 return Result;
5179}
5180
Chris Lattner10c0d912008-04-22 02:53:33 +00005181
5182/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5183/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5184/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5185/// complex, and scales are involved. The above expression would also be legal
5186/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5187/// later form is less amenable to optimization though, and we are allowed to
5188/// generate the first by knowing that pointer arithmetic doesn't overflow.
5189///
5190/// If we can't emit an optimized form for this expression, this returns null.
5191///
5192static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5193 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005194 TargetData &TD = IC.getTargetData();
5195 gep_type_iterator GTI = gep_type_begin(GEP);
5196
5197 // Check to see if this gep only has a single variable index. If so, and if
5198 // any constant indices are a multiple of its scale, then we can compute this
5199 // in terms of the scale of the variable index. For example, if the GEP
5200 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5201 // because the expression will cross zero at the same point.
5202 unsigned i, e = GEP->getNumOperands();
5203 int64_t Offset = 0;
5204 for (i = 1; i != e; ++i, ++GTI) {
5205 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5206 // Compute the aggregate offset of constant indices.
5207 if (CI->isZero()) continue;
5208
5209 // Handle a struct index, which adds its field offset to the pointer.
5210 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5211 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5212 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005213 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005214 Offset += Size*CI->getSExtValue();
5215 }
5216 } else {
5217 // Found our variable index.
5218 break;
5219 }
5220 }
5221
5222 // If there are no variable indices, we must have a constant offset, just
5223 // evaluate it the general way.
5224 if (i == e) return 0;
5225
5226 Value *VariableIdx = GEP->getOperand(i);
5227 // Determine the scale factor of the variable element. For example, this is
5228 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005229 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005230
5231 // Verify that there are no other variable indices. If so, emit the hard way.
5232 for (++i, ++GTI; i != e; ++i, ++GTI) {
5233 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5234 if (!CI) return 0;
5235
5236 // Compute the aggregate offset of constant indices.
5237 if (CI->isZero()) continue;
5238
5239 // Handle a struct index, which adds its field offset to the pointer.
5240 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5241 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5242 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005243 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005244 Offset += Size*CI->getSExtValue();
5245 }
5246 }
5247
5248 // Okay, we know we have a single variable index, which must be a
5249 // pointer/array/vector index. If there is no offset, life is simple, return
5250 // the index.
5251 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5252 if (Offset == 0) {
5253 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5254 // we don't need to bother extending: the extension won't affect where the
5255 // computation crosses zero.
5256 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5257 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5258 VariableIdx->getNameStart(), &I);
5259 return VariableIdx;
5260 }
5261
5262 // Otherwise, there is an index. The computation we will do will be modulo
5263 // the pointer size, so get it.
5264 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5265
5266 Offset &= PtrSizeMask;
5267 VariableScale &= PtrSizeMask;
5268
5269 // To do this transformation, any constant index must be a multiple of the
5270 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5271 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5272 // multiple of the variable scale.
5273 int64_t NewOffs = Offset / (int64_t)VariableScale;
5274 if (Offset != NewOffs*(int64_t)VariableScale)
5275 return 0;
5276
5277 // Okay, we can do this evaluation. Start by converting the index to intptr.
5278 const Type *IntPtrTy = TD.getIntPtrType();
5279 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005280 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005281 true /*SExt*/,
5282 VariableIdx->getNameStart(), &I);
5283 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005284 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005285}
5286
5287
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005289/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5291 ICmpInst::Predicate Cond,
5292 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005293 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005294
Chris Lattner10c0d912008-04-22 02:53:33 +00005295 // Look through bitcasts.
5296 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5297 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005298
Chris Lattner574da9b2005-01-13 20:14:25 +00005299 Value *PtrBase = GEPLHS->getOperand(0);
5300 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005301 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005302 // This transformation (ignoring the base and scales) is valid because we
5303 // know pointers can't overflow. See if we can output an optimized form.
5304 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5305
5306 // If not, synthesize the offset the hard way.
5307 if (Offset == 0)
5308 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005309 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5310 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005311 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005312 // If the base pointers are different, but the indices are the same, just
5313 // compare the base pointer.
5314 if (PtrBase != GEPRHS->getOperand(0)) {
5315 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005316 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005317 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005318 if (IndicesTheSame)
5319 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5320 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5321 IndicesTheSame = false;
5322 break;
5323 }
5324
5325 // If all indices are the same, just compare the base pointers.
5326 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5328 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005329
5330 // Otherwise, the base pointers are different and the indices are
5331 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005332 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005333 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005334
Chris Lattnere9d782b2005-01-13 22:25:21 +00005335 // If one of the GEPs has all zero indices, recurse.
5336 bool AllZeros = true;
5337 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5338 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5339 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5340 AllZeros = false;
5341 break;
5342 }
5343 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005344 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5345 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005346
5347 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005348 AllZeros = true;
5349 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5350 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5351 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5352 AllZeros = false;
5353 break;
5354 }
5355 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005357
Chris Lattner4401c9c2005-01-14 00:20:05 +00005358 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5359 // If the GEPs only differ by one index, compare it.
5360 unsigned NumDifferences = 0; // Keep track of # differences.
5361 unsigned DiffOperand = 0; // The operand that differs.
5362 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5363 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005364 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5365 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005366 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005367 NumDifferences = 2;
5368 break;
5369 } else {
5370 if (NumDifferences++) break;
5371 DiffOperand = i;
5372 }
5373 }
5374
5375 if (NumDifferences == 0) // SAME GEP?
5376 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005377 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005378 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005379
Chris Lattner4401c9c2005-01-14 00:20:05 +00005380 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005381 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5382 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005383 // Make sure we do a signed comparison here.
5384 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005385 }
5386 }
5387
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005389 // the result to fold to a constant!
5390 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5391 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5392 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5393 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5394 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005396 }
5397 }
5398 return 0;
5399}
5400
Chris Lattnera5406232008-05-19 20:18:56 +00005401/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5402///
5403Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5404 Instruction *LHSI,
5405 Constant *RHSC) {
5406 if (!isa<ConstantFP>(RHSC)) return 0;
5407 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5408
5409 // Get the width of the mantissa. We don't want to hack on conversions that
5410 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005411 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005412 if (MantissaWidth == -1) return 0; // Unknown.
5413
5414 // Check to see that the input is converted from an integer type that is small
5415 // enough that preserves all bits. TODO: check here for "known" sign bits.
5416 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5417 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5418
5419 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005420 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5421 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005422 ++InputSize;
5423
5424 // If the conversion would lose info, don't hack on this.
5425 if ((int)InputSize > MantissaWidth)
5426 return 0;
5427
5428 // Otherwise, we can potentially simplify the comparison. We know that it
5429 // will always come through as an integer value and we know the constant is
5430 // not a NAN (it would have been previously simplified).
5431 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5432
5433 ICmpInst::Predicate Pred;
5434 switch (I.getPredicate()) {
5435 default: assert(0 && "Unexpected predicate!");
5436 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005437 case FCmpInst::FCMP_OEQ:
5438 Pred = ICmpInst::ICMP_EQ;
5439 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005440 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005441 case FCmpInst::FCMP_OGT:
5442 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5443 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005444 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005445 case FCmpInst::FCMP_OGE:
5446 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5447 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005448 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005449 case FCmpInst::FCMP_OLT:
5450 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5451 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005452 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005453 case FCmpInst::FCMP_OLE:
5454 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5455 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005456 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005457 case FCmpInst::FCMP_ONE:
5458 Pred = ICmpInst::ICMP_NE;
5459 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005460 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005461 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005462 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005463 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005464 }
5465
5466 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5467
5468 // Now we know that the APFloat is a normal number, zero or inf.
5469
Chris Lattner85162782008-05-20 03:50:52 +00005470 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005471 // comparing an i8 to 300.0.
5472 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5473
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005474 if (!LHSUnsigned) {
5475 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5476 // and large values.
5477 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5478 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5479 APFloat::rmNearestTiesToEven);
5480 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5481 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5482 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005483 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5484 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005485 }
5486 } else {
5487 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5488 // +INF and large values.
5489 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5490 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5491 APFloat::rmNearestTiesToEven);
5492 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5493 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5494 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005495 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5496 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005497 }
Chris Lattnera5406232008-05-19 20:18:56 +00005498 }
5499
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005500 if (!LHSUnsigned) {
5501 // See if the RHS value is < SignedMin.
5502 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5503 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5504 APFloat::rmNearestTiesToEven);
5505 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5506 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5507 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005508 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5509 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005510 }
Chris Lattnera5406232008-05-19 20:18:56 +00005511 }
5512
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005513 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5514 // [0, UMAX], but it may still be fractional. See if it is fractional by
5515 // casting the FP value to the integer value and back, checking for equality.
5516 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005517 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5518 if (!RHS.isZero() &&
5519 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005520 // If we had a comparison against a fractional value, we have to adjust the
5521 // compare predicate and sometimes the value. RHSC is rounded towards zero
5522 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005523 switch (Pred) {
5524 default: assert(0 && "Unexpected integer comparison!");
5525 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005526 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005527 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005528 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005529 case ICmpInst::ICMP_ULE:
5530 // (float)int <= 4.4 --> int <= 4
5531 // (float)int <= -4.4 --> false
5532 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005533 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005534 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005535 case ICmpInst::ICMP_SLE:
5536 // (float)int <= 4.4 --> int <= 4
5537 // (float)int <= -4.4 --> int < -4
5538 if (RHS.isNegative())
5539 Pred = ICmpInst::ICMP_SLT;
5540 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005541 case ICmpInst::ICMP_ULT:
5542 // (float)int < -4.4 --> false
5543 // (float)int < 4.4 --> int <= 4
5544 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005545 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005546 Pred = ICmpInst::ICMP_ULE;
5547 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005548 case ICmpInst::ICMP_SLT:
5549 // (float)int < -4.4 --> int < -4
5550 // (float)int < 4.4 --> int <= 4
5551 if (!RHS.isNegative())
5552 Pred = ICmpInst::ICMP_SLE;
5553 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005554 case ICmpInst::ICMP_UGT:
5555 // (float)int > 4.4 --> int > 4
5556 // (float)int > -4.4 --> true
5557 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005558 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005559 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005560 case ICmpInst::ICMP_SGT:
5561 // (float)int > 4.4 --> int > 4
5562 // (float)int > -4.4 --> int >= -4
5563 if (RHS.isNegative())
5564 Pred = ICmpInst::ICMP_SGE;
5565 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005566 case ICmpInst::ICMP_UGE:
5567 // (float)int >= -4.4 --> true
5568 // (float)int >= 4.4 --> int > 4
5569 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005570 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005571 Pred = ICmpInst::ICMP_UGT;
5572 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005573 case ICmpInst::ICMP_SGE:
5574 // (float)int >= -4.4 --> int >= -4
5575 // (float)int >= 4.4 --> int > 4
5576 if (!RHS.isNegative())
5577 Pred = ICmpInst::ICMP_SGT;
5578 break;
5579 }
5580 }
5581
5582 // Lower this FP comparison into an appropriate integer version of the
5583 // comparison.
5584 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5585}
5586
Reid Spencere4d87aa2006-12-23 06:05:41 +00005587Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5588 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005590
Chris Lattner58e97462007-01-14 19:42:17 +00005591 // Fold trivial predicates.
5592 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005594 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005595 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005596
5597 // Simplify 'fcmp pred X, X'
5598 if (Op0 == Op1) {
5599 switch (I.getPredicate()) {
5600 default: assert(0 && "Unknown predicate!");
5601 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5602 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5603 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005604 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005605 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5606 case FCmpInst::FCMP_OLT: // True if ordered and less than
5607 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005608 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005609
5610 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5611 case FCmpInst::FCMP_ULT: // True if unordered or less than
5612 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5613 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5614 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5615 I.setPredicate(FCmpInst::FCMP_UNO);
5616 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5617 return &I;
5618
5619 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5620 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5621 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5622 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5623 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5624 I.setPredicate(FCmpInst::FCMP_ORD);
5625 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5626 return &I;
5627 }
5628 }
5629
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005631 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005632
Reid Spencere4d87aa2006-12-23 06:05:41 +00005633 // Handle fcmp with constant RHS
5634 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005635 // If the constant is a nan, see if we can fold the comparison based on it.
5636 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5637 if (CFP->getValueAPF().isNaN()) {
5638 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005639 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005640 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5641 "Comparison must be either ordered or unordered!");
5642 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005643 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005644 }
5645 }
5646
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5648 switch (LHSI->getOpcode()) {
5649 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005650 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5651 // block. If in the same block, we're encouraging jump threading. If
5652 // not, we are just pessimizing the code by making an i1 phi.
5653 if (LHSI->getParent() == I.getParent())
5654 if (Instruction *NV = FoldOpIntoPhi(I))
5655 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005656 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005657 case Instruction::SIToFP:
5658 case Instruction::UIToFP:
5659 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5660 return NV;
5661 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005662 case Instruction::Select:
5663 // If either operand of the select is a constant, we can fold the
5664 // comparison into the select arms, which will cause one to be
5665 // constant folded and the select turned into a bitwise or.
5666 Value *Op1 = 0, *Op2 = 0;
5667 if (LHSI->hasOneUse()) {
5668 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5669 // Fold the known value into the constant operand.
5670 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5671 // Insert a new FCmp of the other select operand.
5672 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5673 LHSI->getOperand(2), RHSC,
5674 I.getName()), I);
5675 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5676 // Fold the known value into the constant operand.
5677 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5678 // Insert a new FCmp of the other select operand.
5679 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5680 LHSI->getOperand(1), RHSC,
5681 I.getName()), I);
5682 }
5683 }
5684
5685 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005686 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005687 break;
5688 }
5689 }
5690
5691 return Changed ? &I : 0;
5692}
5693
5694Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5695 bool Changed = SimplifyCompare(I);
5696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5697 const Type *Ty = Op0->getType();
5698
5699 // icmp X, X
5700 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005701 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005702 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703
5704 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005705 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005706
Reid Spencere4d87aa2006-12-23 06:05:41 +00005707 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005708 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005709 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5710 isa<ConstantPointerNull>(Op0)) &&
5711 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005712 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005713 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005714 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005715
Reid Spencere4d87aa2006-12-23 06:05:41 +00005716 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005717 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 switch (I.getPredicate()) {
5719 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005720 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005721 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005722 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005723 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005724 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005725 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005726 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005727
Reid Spencere4d87aa2006-12-23 06:05:41 +00005728 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005729 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005730 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005731 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005732 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005733 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005734 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005735 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005736 case ICmpInst::ICMP_SGT:
5737 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005738 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005739 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5740 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5741 InsertNewInstBefore(Not, I);
5742 return BinaryOperator::CreateAnd(Not, Op0);
5743 }
5744 case ICmpInst::ICMP_UGE:
5745 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5746 // FALL THROUGH
5747 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005748 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005749 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005750 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005751 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005752 case ICmpInst::ICMP_SGE:
5753 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5754 // FALL THROUGH
5755 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5756 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5757 InsertNewInstBefore(Not, I);
5758 return BinaryOperator::CreateOr(Not, Op0);
5759 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005760 }
Chris Lattner8b170942002-08-09 23:47:40 +00005761 }
5762
Dan Gohman81b28ce2008-09-16 18:46:06 +00005763 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005764 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005765 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005766
Chris Lattnerb6566012008-01-05 01:18:20 +00005767 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5768 if (I.isEquality() && CI->isNullValue() &&
5769 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5770 // (icmp cond A B) if cond is equality
5771 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005772 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005773
Dan Gohman81b28ce2008-09-16 18:46:06 +00005774 // If we have an icmp le or icmp ge instruction, turn it into the
5775 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5776 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005777 switch (I.getPredicate()) {
5778 default: break;
5779 case ICmpInst::ICMP_ULE:
5780 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5781 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5782 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5783 case ICmpInst::ICMP_SLE:
5784 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5785 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5786 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5787 case ICmpInst::ICMP_UGE:
5788 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5789 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5790 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5791 case ICmpInst::ICMP_SGE:
5792 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5793 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5794 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5795 }
5796
Chris Lattner183661e2008-07-11 05:40:05 +00005797 // See if we can fold the comparison based on range information we can get
5798 // by checking whether bits are known to be zero or one in the input.
5799 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5800 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5801
5802 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005803 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005804 bool UnusedBit;
5805 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5806
Chris Lattner886ab6c2009-01-31 08:15:18 +00005807 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005808 isSignBit ? APInt::getSignBit(BitWidth)
5809 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005810 KnownZero, KnownOne, 0))
5811 return &I;
5812
5813 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005814 // in. Compute the Min, Max and RHS values based on the known bits. For the
5815 // EQ and NE we use unsigned values.
5816 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005817 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5818 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5819 else
5820 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5821
Chris Lattner183661e2008-07-11 05:40:05 +00005822 // If Min and Max are known to be the same, then SimplifyDemandedBits
5823 // figured out that the LHS is a constant. Just constant fold this now so
5824 // that code below can assume that Min != Max.
5825 if (Min == Max)
5826 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5827 ConstantInt::get(Min),
5828 CI));
5829
5830 // Based on the range information we know about the LHS, see if we can
5831 // simplify this comparison. For example, (x&4) < 8 is always true.
5832 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005833 switch (I.getPredicate()) { // LE/GE have been folded already.
5834 default: assert(0 && "Unknown icmp opcode!");
5835 case ICmpInst::ICMP_EQ:
5836 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5837 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5838 break;
5839 case ICmpInst::ICMP_NE:
5840 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5841 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842 break;
5843 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005844 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005846 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005848 if (RHSVal == Max) // A <u MAX -> A != MAX
5849 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5850 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5851 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5852
5853 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5854 if (CI->isMinValue(true))
5855 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5856 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005857 break;
5858 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005859 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005860 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005861 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005863
5864 if (RHSVal == Min) // A >u MIN -> A != MIN
5865 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5866 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5867 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5868
5869 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5870 if (CI->isMaxValue(true))
5871 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5872 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005873 break;
5874 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005875 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005876 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005877 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005878 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005879 if (RHSVal == Max) // A <s MAX -> A != MAX
5880 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005881 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005882 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005883 break;
5884 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005885 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005887 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005889
5890 if (RHSVal == Min) // A >s MIN -> A != MIN
5891 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5892 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5893 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005894 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005895 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005896 }
5897
5898 // Test if the ICmpInst instruction is used exclusively by a select as
5899 // part of a minimum or maximum operation. If so, refrain from doing
5900 // any other folding. This helps out other analyses which understand
5901 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5902 // and CodeGen. And in this case, at least one of the comparison
5903 // operands has at least one user besides the compare (the select),
5904 // which would often largely negate the benefit of folding anyway.
5905 if (I.hasOneUse())
5906 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5907 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5908 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5909 return 0;
5910
5911 // See if we are doing a comparison between a constant and an instruction that
5912 // can be folded into the comparison.
5913 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005915 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005917 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005918 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5919 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005920 }
5921
Chris Lattner01deb9d2007-04-03 17:43:25 +00005922 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005923 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5924 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5925 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005926 case Instruction::GetElementPtr:
5927 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005929 bool isAllZeros = true;
5930 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5931 if (!isa<Constant>(LHSI->getOperand(i)) ||
5932 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5933 isAllZeros = false;
5934 break;
5935 }
5936 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005938 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5939 }
5940 break;
5941
Chris Lattner6970b662005-04-23 15:31:55 +00005942 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005943 // Only fold icmp into the PHI if the phi and fcmp are in the same
5944 // block. If in the same block, we're encouraging jump threading. If
5945 // not, we are just pessimizing the code by making an i1 phi.
5946 if (LHSI->getParent() == I.getParent())
5947 if (Instruction *NV = FoldOpIntoPhi(I))
5948 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005949 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005950 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005951 // If either operand of the select is a constant, we can fold the
5952 // comparison into the select arms, which will cause one to be
5953 // constant folded and the select turned into a bitwise or.
5954 Value *Op1 = 0, *Op2 = 0;
5955 if (LHSI->hasOneUse()) {
5956 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5959 // Insert a new ICmp of the other select operand.
5960 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5961 LHSI->getOperand(2), RHSC,
5962 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005963 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5966 // Insert a new ICmp of the other select operand.
5967 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5968 LHSI->getOperand(1), RHSC,
5969 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005970 }
5971 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005972
Chris Lattner6970b662005-04-23 15:31:55 +00005973 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005974 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005975 break;
5976 }
Chris Lattner4802d902007-04-06 18:57:34 +00005977 case Instruction::Malloc:
5978 // If we have (malloc != null), and if the malloc has a single use, we
5979 // can assume it is successful and remove the malloc.
5980 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5981 AddToWorkList(LHSI);
5982 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005983 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005984 }
5985 break;
5986 }
Chris Lattner6970b662005-04-23 15:31:55 +00005987 }
5988
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005990 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005992 return NI;
5993 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5995 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005996 return NI;
5997
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005999 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6000 // now.
6001 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6002 if (isa<PointerType>(Op0->getType()) &&
6003 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006004 // We keep moving the cast from the left operand over to the right
6005 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006006 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006007
Chris Lattner57d86372007-01-06 01:45:59 +00006008 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6009 // so eliminate it as well.
6010 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6011 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006012
Chris Lattnerde90b762003-11-03 04:25:02 +00006013 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006014 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006015 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006016 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006017 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006019 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006020 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006021 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006022 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006023 }
Chris Lattner57d86372007-01-06 01:45:59 +00006024 }
6025
6026 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006027 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006028 // This comes up when you have code like
6029 // int X = A < B;
6030 // if (X) ...
6031 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006032 // with a constant or another cast from the same type.
6033 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006034 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006035 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006036 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006037
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006038 // See if it's the same type of instruction on the left and right.
6039 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6040 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006041 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6042 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6043 I.isEquality()) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006044 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006045 default: break;
6046 case Instruction::Add:
6047 case Instruction::Sub:
6048 case Instruction::Xor:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006049 // a+x icmp eq/ne b+x --> a icmp b
6050 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6051 Op1I->getOperand(0));
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006052 break;
6053 case Instruction::Mul:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006054 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6055 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6056 // Mask = -1 >> count-trailing-zeros(Cst).
6057 if (!CI->isZero() && !CI->isOne()) {
6058 const APInt &AP = CI->getValue();
6059 ConstantInt *Mask = ConstantInt::get(
6060 APInt::getLowBitsSet(AP.getBitWidth(),
6061 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006062 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006063 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6064 Mask);
6065 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6066 Mask);
6067 InsertNewInstBefore(And1, I);
6068 InsertNewInstBefore(And2, I);
6069 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006070 }
6071 }
6072 break;
6073 }
6074 }
6075 }
6076 }
6077
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006078 // ~x < ~y --> y < x
6079 { Value *A, *B;
6080 if (match(Op0, m_Not(m_Value(A))) &&
6081 match(Op1, m_Not(m_Value(B))))
6082 return new ICmpInst(I.getPredicate(), B, A);
6083 }
6084
Chris Lattner65b72ba2006-09-18 04:22:48 +00006085 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006086 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006087
6088 // -x == -y --> x == y
6089 if (match(Op0, m_Neg(m_Value(A))) &&
6090 match(Op1, m_Neg(m_Value(B))))
6091 return new ICmpInst(I.getPredicate(), A, B);
6092
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006093 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6094 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6095 Value *OtherVal = A == Op1 ? B : A;
6096 return new ICmpInst(I.getPredicate(), OtherVal,
6097 Constant::getNullValue(A->getType()));
6098 }
6099
6100 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6101 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006102 ConstantInt *C1, *C2;
6103 if (match(B, m_ConstantInt(C1)) &&
6104 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6105 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6106 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6107 return new ICmpInst(I.getPredicate(), A,
6108 InsertNewInstBefore(Xor, I));
6109 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006110
6111 // A^B == A^D -> B == D
6112 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6113 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6114 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6115 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6116 }
6117 }
6118
6119 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6120 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006121 // A == (A^B) -> B == 0
6122 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006123 return new ICmpInst(I.getPredicate(), OtherVal,
6124 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006125 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006126
6127 // (A-B) == A -> B == 0
6128 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6129 return new ICmpInst(I.getPredicate(), B,
6130 Constant::getNullValue(B->getType()));
6131
6132 // A == (A-B) -> B == 0
6133 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006134 return new ICmpInst(I.getPredicate(), B,
6135 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006136
Chris Lattner9c2328e2006-11-14 06:06:06 +00006137 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6138 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6139 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6140 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6141 Value *X = 0, *Y = 0, *Z = 0;
6142
6143 if (A == C) {
6144 X = B; Y = D; Z = A;
6145 } else if (A == D) {
6146 X = B; Y = C; Z = A;
6147 } else if (B == C) {
6148 X = A; Y = D; Z = B;
6149 } else if (B == D) {
6150 X = A; Y = C; Z = B;
6151 }
6152
6153 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006154 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6155 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006156 I.setOperand(0, Op1);
6157 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6158 return &I;
6159 }
6160 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006161 }
Chris Lattner7e708292002-06-25 16:13:24 +00006162 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006163}
6164
Chris Lattner562ef782007-06-20 23:46:26 +00006165
6166/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6167/// and CmpRHS are both known to be integer constants.
6168Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6169 ConstantInt *DivRHS) {
6170 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6171 const APInt &CmpRHSV = CmpRHS->getValue();
6172
6173 // FIXME: If the operand types don't match the type of the divide
6174 // then don't attempt this transform. The code below doesn't have the
6175 // logic to deal with a signed divide and an unsigned compare (and
6176 // vice versa). This is because (x /s C1) <s C2 produces different
6177 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6178 // (x /u C1) <u C2. Simply casting the operands and result won't
6179 // work. :( The if statement below tests that condition and bails
6180 // if it finds it.
6181 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6182 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6183 return 0;
6184 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006185 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006186 if (DivIsSigned && DivRHS->isAllOnesValue())
6187 return 0; // The overflow computation also screws up here
6188 if (DivRHS->isOne())
6189 return 0; // Not worth bothering, and eliminates some funny cases
6190 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006191
6192 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6193 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6194 // C2 (CI). By solving for X we can turn this into a range check
6195 // instead of computing a divide.
6196 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6197
6198 // Determine if the product overflows by seeing if the product is
6199 // not equal to the divide. Make sure we do the same kind of divide
6200 // as in the LHS instruction that we're folding.
6201 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6202 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6203
6204 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006205 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006206
Chris Lattner1dbfd482007-06-21 18:11:19 +00006207 // Figure out the interval that is being checked. For example, a comparison
6208 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6209 // Compute this interval based on the constants involved and the signedness of
6210 // the compare/divide. This computes a half-open interval, keeping track of
6211 // whether either value in the interval overflows. After analysis each
6212 // overflow variable is set to 0 if it's corresponding bound variable is valid
6213 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6214 int LoOverflow = 0, HiOverflow = 0;
6215 ConstantInt *LoBound = 0, *HiBound = 0;
6216
Chris Lattner562ef782007-06-20 23:46:26 +00006217 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006218 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006219 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006220 HiOverflow = LoOverflow = ProdOV;
6221 if (!HiOverflow)
6222 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006223 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006224 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006225 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006226 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6227 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006228 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006229 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6230 HiOverflow = LoOverflow = ProdOV;
6231 if (!HiOverflow)
6232 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006233 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006234 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006235 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006236 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6237 if (!LoOverflow) {
6238 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6239 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6240 true) ? -1 : 0;
6241 }
Chris Lattner562ef782007-06-20 23:46:26 +00006242 }
Dan Gohman76491272008-02-13 22:09:18 +00006243 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006244 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006245 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006246 LoBound = AddOne(DivRHS);
6247 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006248 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6249 HiOverflow = 1; // [INTMIN+1, overflow)
6250 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6251 }
Dan Gohman76491272008-02-13 22:09:18 +00006252 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006254 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006255 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006256 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006257 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006258 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006259 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6260 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006261 if (!HiOverflow)
6262 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006263 }
6264
Chris Lattner1dbfd482007-06-21 18:11:19 +00006265 // Dividing by a negative swaps the condition. LT <-> GT
6266 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006267 }
6268
6269 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006270 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006271 default: assert(0 && "Unhandled icmp opcode!");
6272 case ICmpInst::ICMP_EQ:
6273 if (LoOverflow && HiOverflow)
6274 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6275 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006276 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006277 ICmpInst::ICMP_UGE, X, LoBound);
6278 else if (LoOverflow)
6279 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6280 ICmpInst::ICMP_ULT, X, HiBound);
6281 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006282 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006283 case ICmpInst::ICMP_NE:
6284 if (LoOverflow && HiOverflow)
6285 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6286 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006287 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006288 ICmpInst::ICMP_ULT, X, LoBound);
6289 else if (LoOverflow)
6290 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6291 ICmpInst::ICMP_UGE, X, HiBound);
6292 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006293 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006294 case ICmpInst::ICMP_ULT:
6295 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006296 if (LoOverflow == +1) // Low bound is greater than input range.
6297 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006299 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006300 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006301 case ICmpInst::ICMP_UGT:
6302 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006303 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006304 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006305 else if (HiOverflow == -1) // High bound less than input range.
6306 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6307 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006308 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6309 else
6310 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6311 }
6312}
6313
6314
Chris Lattner01deb9d2007-04-03 17:43:25 +00006315/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6316///
6317Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6318 Instruction *LHSI,
6319 ConstantInt *RHS) {
6320 const APInt &RHSV = RHS->getValue();
6321
6322 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006323 case Instruction::Trunc:
6324 if (ICI.isEquality() && LHSI->hasOneUse()) {
6325 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6326 // of the high bits truncated out of x are known.
6327 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6328 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6329 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6330 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6331 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6332
6333 // If all the high bits are known, we can do this xform.
6334 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6335 // Pull in the high bits from known-ones set.
6336 APInt NewRHS(RHS->getValue());
6337 NewRHS.zext(SrcBits);
6338 NewRHS |= KnownOne;
6339 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6340 ConstantInt::get(NewRHS));
6341 }
6342 }
6343 break;
6344
Duncan Sands0091bf22007-04-04 06:42:45 +00006345 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006346 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6347 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6348 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006349 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6350 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006351 Value *CompareVal = LHSI->getOperand(0);
6352
6353 // If the sign bit of the XorCST is not set, there is no change to
6354 // the operation, just stop using the Xor.
6355 if (!XorCST->getValue().isNegative()) {
6356 ICI.setOperand(0, CompareVal);
6357 AddToWorkList(LHSI);
6358 return &ICI;
6359 }
6360
6361 // Was the old condition true if the operand is positive?
6362 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6363
6364 // If so, the new one isn't.
6365 isTrueIfPositive ^= true;
6366
6367 if (isTrueIfPositive)
6368 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6369 else
6370 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6371 }
6372 }
6373 break;
6374 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6375 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6376 LHSI->getOperand(0)->hasOneUse()) {
6377 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6378
6379 // If the LHS is an AND of a truncating cast, we can widen the
6380 // and/compare to be the input width without changing the value
6381 // produced, eliminating a cast.
6382 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6383 // We can do this transformation if either the AND constant does not
6384 // have its sign bit set or if it is an equality comparison.
6385 // Extending a relational comparison when we're checking the sign
6386 // bit would not work.
6387 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006388 (ICI.isEquality() ||
6389 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006390 uint32_t BitWidth =
6391 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6392 APInt NewCST = AndCST->getValue();
6393 NewCST.zext(BitWidth);
6394 APInt NewCI = RHSV;
6395 NewCI.zext(BitWidth);
6396 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006397 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006398 ConstantInt::get(NewCST),LHSI->getName());
6399 InsertNewInstBefore(NewAnd, ICI);
6400 return new ICmpInst(ICI.getPredicate(), NewAnd,
6401 ConstantInt::get(NewCI));
6402 }
6403 }
6404
6405 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6406 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6407 // happens a LOT in code produced by the C front-end, for bitfield
6408 // access.
6409 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6410 if (Shift && !Shift->isShift())
6411 Shift = 0;
6412
6413 ConstantInt *ShAmt;
6414 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6415 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6416 const Type *AndTy = AndCST->getType(); // Type of the and.
6417
6418 // We can fold this as long as we can't shift unknown bits
6419 // into the mask. This can only happen with signed shift
6420 // rights, as they sign-extend.
6421 if (ShAmt) {
6422 bool CanFold = Shift->isLogicalShift();
6423 if (!CanFold) {
6424 // To test for the bad case of the signed shr, see if any
6425 // of the bits shifted in could be tested after the mask.
6426 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6427 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6428
6429 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6430 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6431 AndCST->getValue()) == 0)
6432 CanFold = true;
6433 }
6434
6435 if (CanFold) {
6436 Constant *NewCst;
6437 if (Shift->getOpcode() == Instruction::Shl)
6438 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6439 else
6440 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6441
6442 // Check to see if we are shifting out any of the bits being
6443 // compared.
6444 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6445 // If we shifted bits out, the fold is not going to work out.
6446 // As a special case, check to see if this means that the
6447 // result is always true or false now.
6448 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6449 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6450 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6451 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6452 } else {
6453 ICI.setOperand(1, NewCst);
6454 Constant *NewAndCST;
6455 if (Shift->getOpcode() == Instruction::Shl)
6456 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6457 else
6458 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6459 LHSI->setOperand(1, NewAndCST);
6460 LHSI->setOperand(0, Shift->getOperand(0));
6461 AddToWorkList(Shift); // Shift is dead.
6462 AddUsesToWorkList(ICI);
6463 return &ICI;
6464 }
6465 }
6466 }
6467
6468 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6469 // preferable because it allows the C<<Y expression to be hoisted out
6470 // of a loop if Y is invariant and X is not.
6471 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6472 ICI.isEquality() && !Shift->isArithmeticShift() &&
6473 isa<Instruction>(Shift->getOperand(0))) {
6474 // Compute C << Y.
6475 Value *NS;
6476 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006477 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006478 Shift->getOperand(1), "tmp");
6479 } else {
6480 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006481 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006482 Shift->getOperand(1), "tmp");
6483 }
6484 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6485
6486 // Compute X & (C << Y).
6487 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006488 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006489 InsertNewInstBefore(NewAnd, ICI);
6490
6491 ICI.setOperand(0, NewAnd);
6492 return &ICI;
6493 }
6494 }
6495 break;
6496
Chris Lattnera0141b92007-07-15 20:42:37 +00006497 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6498 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6499 if (!ShAmt) break;
6500
6501 uint32_t TypeBits = RHSV.getBitWidth();
6502
6503 // Check that the shift amount is in range. If not, don't perform
6504 // undefined shifts. When the shift is visited it will be
6505 // simplified.
6506 if (ShAmt->uge(TypeBits))
6507 break;
6508
6509 if (ICI.isEquality()) {
6510 // If we are comparing against bits always shifted out, the
6511 // comparison cannot succeed.
6512 Constant *Comp =
6513 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6514 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6515 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6516 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6517 return ReplaceInstUsesWith(ICI, Cst);
6518 }
6519
6520 if (LHSI->hasOneUse()) {
6521 // Otherwise strength reduce the shift into an and.
6522 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6523 Constant *Mask =
6524 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006525
Chris Lattnera0141b92007-07-15 20:42:37 +00006526 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006527 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006528 Mask, LHSI->getName()+".mask");
6529 Value *And = InsertNewInstBefore(AndI, ICI);
6530 return new ICmpInst(ICI.getPredicate(), And,
6531 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006532 }
6533 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006534
6535 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6536 bool TrueIfSigned = false;
6537 if (LHSI->hasOneUse() &&
6538 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6539 // (X << 31) <s 0 --> (X&1) != 0
6540 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6541 (TypeBits-ShAmt->getZExtValue()-1));
6542 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006543 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006544 Mask, LHSI->getName()+".mask");
6545 Value *And = InsertNewInstBefore(AndI, ICI);
6546
6547 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6548 And, Constant::getNullValue(And->getType()));
6549 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006550 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006551 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006552
6553 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006554 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006555 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006556 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006557 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006558
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006559 // Check that the shift amount is in range. If not, don't perform
6560 // undefined shifts. When the shift is visited it will be
6561 // simplified.
6562 uint32_t TypeBits = RHSV.getBitWidth();
6563 if (ShAmt->uge(TypeBits))
6564 break;
6565
6566 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006567
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006568 // If we are comparing against bits always shifted out, the
6569 // comparison cannot succeed.
6570 APInt Comp = RHSV << ShAmtVal;
6571 if (LHSI->getOpcode() == Instruction::LShr)
6572 Comp = Comp.lshr(ShAmtVal);
6573 else
6574 Comp = Comp.ashr(ShAmtVal);
6575
6576 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6577 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6578 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6579 return ReplaceInstUsesWith(ICI, Cst);
6580 }
6581
6582 // Otherwise, check to see if the bits shifted out are known to be zero.
6583 // If so, we can compare against the unshifted value:
6584 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006585 if (LHSI->hasOneUse() &&
6586 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006587 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6588 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6589 ConstantExpr::getShl(RHS, ShAmt));
6590 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006591
Evan Chengf30752c2008-04-23 00:38:06 +00006592 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006593 // Otherwise strength reduce the shift into an and.
6594 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6595 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006596
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006597 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006598 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006599 Mask, LHSI->getName()+".mask");
6600 Value *And = InsertNewInstBefore(AndI, ICI);
6601 return new ICmpInst(ICI.getPredicate(), And,
6602 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006603 }
6604 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006605 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006606
6607 case Instruction::SDiv:
6608 case Instruction::UDiv:
6609 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6610 // Fold this div into the comparison, producing a range check.
6611 // Determine, based on the divide type, what the range is being
6612 // checked. If there is an overflow on the low or high side, remember
6613 // it, otherwise compute the range [low, hi) bounding the new value.
6614 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006615 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6616 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6617 DivRHS))
6618 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006619 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006620
6621 case Instruction::Add:
6622 // Fold: icmp pred (add, X, C1), C2
6623
6624 if (!ICI.isEquality()) {
6625 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6626 if (!LHSC) break;
6627 const APInt &LHSV = LHSC->getValue();
6628
6629 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6630 .subtract(LHSV);
6631
6632 if (ICI.isSignedPredicate()) {
6633 if (CR.getLower().isSignBit()) {
6634 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6635 ConstantInt::get(CR.getUpper()));
6636 } else if (CR.getUpper().isSignBit()) {
6637 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6638 ConstantInt::get(CR.getLower()));
6639 }
6640 } else {
6641 if (CR.getLower().isMinValue()) {
6642 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6643 ConstantInt::get(CR.getUpper()));
6644 } else if (CR.getUpper().isMinValue()) {
6645 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6646 ConstantInt::get(CR.getLower()));
6647 }
6648 }
6649 }
6650 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006651 }
6652
6653 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6654 if (ICI.isEquality()) {
6655 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6656
6657 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6658 // the second operand is a constant, simplify a bit.
6659 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6660 switch (BO->getOpcode()) {
6661 case Instruction::SRem:
6662 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6663 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6664 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6665 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6666 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006667 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006668 BO->getName());
6669 InsertNewInstBefore(NewRem, ICI);
6670 return new ICmpInst(ICI.getPredicate(), NewRem,
6671 Constant::getNullValue(BO->getType()));
6672 }
6673 }
6674 break;
6675 case Instruction::Add:
6676 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6677 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6678 if (BO->hasOneUse())
6679 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6680 Subtract(RHS, BOp1C));
6681 } else if (RHSV == 0) {
6682 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6683 // efficiently invertible, or if the add has just this one use.
6684 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6685
6686 if (Value *NegVal = dyn_castNegVal(BOp1))
6687 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6688 else if (Value *NegVal = dyn_castNegVal(BOp0))
6689 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6690 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006691 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006692 InsertNewInstBefore(Neg, ICI);
6693 Neg->takeName(BO);
6694 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6695 }
6696 }
6697 break;
6698 case Instruction::Xor:
6699 // For the xor case, we can xor two constants together, eliminating
6700 // the explicit xor.
6701 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6702 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6703 ConstantExpr::getXor(RHS, BOC));
6704
6705 // FALLTHROUGH
6706 case Instruction::Sub:
6707 // Replace (([sub|xor] A, B) != 0) with (A != B)
6708 if (RHSV == 0)
6709 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6710 BO->getOperand(1));
6711 break;
6712
6713 case Instruction::Or:
6714 // If bits are being or'd in that are not present in the constant we
6715 // are comparing against, then the comparison could never succeed!
6716 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6717 Constant *NotCI = ConstantExpr::getNot(RHS);
6718 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6719 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6720 isICMP_NE));
6721 }
6722 break;
6723
6724 case Instruction::And:
6725 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6726 // If bits are being compared against that are and'd out, then the
6727 // comparison can never succeed!
6728 if ((RHSV & ~BOC->getValue()) != 0)
6729 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6730 isICMP_NE));
6731
6732 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6733 if (RHS == BOC && RHSV.isPowerOf2())
6734 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6735 ICmpInst::ICMP_NE, LHSI,
6736 Constant::getNullValue(RHS->getType()));
6737
6738 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006739 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006740 Value *X = BO->getOperand(0);
6741 Constant *Zero = Constant::getNullValue(X->getType());
6742 ICmpInst::Predicate pred = isICMP_NE ?
6743 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6744 return new ICmpInst(pred, X, Zero);
6745 }
6746
6747 // ((X & ~7) == 0) --> X < 8
6748 if (RHSV == 0 && isHighOnes(BOC)) {
6749 Value *X = BO->getOperand(0);
6750 Constant *NegX = ConstantExpr::getNeg(BOC);
6751 ICmpInst::Predicate pred = isICMP_NE ?
6752 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6753 return new ICmpInst(pred, X, NegX);
6754 }
6755 }
6756 default: break;
6757 }
6758 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6759 // Handle icmp {eq|ne} <intrinsic>, intcst.
6760 if (II->getIntrinsicID() == Intrinsic::bswap) {
6761 AddToWorkList(II);
6762 ICI.setOperand(0, II->getOperand(1));
6763 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6764 return &ICI;
6765 }
6766 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006767 }
6768 return 0;
6769}
6770
6771/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6772/// We only handle extending casts so far.
6773///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006774Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6775 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006776 Value *LHSCIOp = LHSCI->getOperand(0);
6777 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006778 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006779 Value *RHSCIOp;
6780
Chris Lattner8c756c12007-05-05 22:41:33 +00006781 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6782 // integer type is the same size as the pointer type.
6783 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6784 getTargetData().getPointerSizeInBits() ==
6785 cast<IntegerType>(DestTy)->getBitWidth()) {
6786 Value *RHSOp = 0;
6787 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006788 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006789 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6790 RHSOp = RHSC->getOperand(0);
6791 // If the pointer types don't match, insert a bitcast.
6792 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006793 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006794 }
6795
6796 if (RHSOp)
6797 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6798 }
6799
6800 // The code below only handles extension cast instructions, so far.
6801 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006802 if (LHSCI->getOpcode() != Instruction::ZExt &&
6803 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006804 return 0;
6805
Reid Spencere4d87aa2006-12-23 06:05:41 +00006806 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6807 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006808
Reid Spencere4d87aa2006-12-23 06:05:41 +00006809 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006810 // Not an extension from the same type?
6811 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006812 if (RHSCIOp->getType() != LHSCIOp->getType())
6813 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006814
Nick Lewycky4189a532008-01-28 03:48:02 +00006815 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006816 // and the other is a zext), then we can't handle this.
6817 if (CI->getOpcode() != LHSCI->getOpcode())
6818 return 0;
6819
Nick Lewycky4189a532008-01-28 03:48:02 +00006820 // Deal with equality cases early.
6821 if (ICI.isEquality())
6822 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6823
6824 // A signed comparison of sign extended values simplifies into a
6825 // signed comparison.
6826 if (isSignedCmp && isSignedExt)
6827 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6828
6829 // The other three cases all fold into an unsigned comparison.
6830 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006831 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006832
Reid Spencere4d87aa2006-12-23 06:05:41 +00006833 // If we aren't dealing with a constant on the RHS, exit early
6834 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6835 if (!CI)
6836 return 0;
6837
6838 // Compute the constant that would happen if we truncated to SrcTy then
6839 // reextended to DestTy.
6840 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6841 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6842
6843 // If the re-extended constant didn't change...
6844 if (Res2 == CI) {
6845 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6846 // For example, we might have:
6847 // %A = sext short %X to uint
6848 // %B = icmp ugt uint %A, 1330
6849 // It is incorrect to transform this into
6850 // %B = icmp ugt short %X, 1330
6851 // because %A may have negative value.
6852 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006853 // However, we allow this when the compare is EQ/NE, because they are
6854 // signless.
6855 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006856 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006857 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006858 }
6859
6860 // The re-extended constant changed so the constant cannot be represented
6861 // in the shorter type. Consequently, we cannot emit a simple comparison.
6862
6863 // First, handle some easy cases. We know the result cannot be equal at this
6864 // point so handle the ICI.isEquality() cases
6865 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006866 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006867 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006868 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006869
6870 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6871 // should have been folded away previously and not enter in here.
6872 Value *Result;
6873 if (isSignedCmp) {
6874 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006875 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006876 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006877 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006878 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006879 } else {
6880 // We're performing an unsigned comparison.
6881 if (isSignedExt) {
6882 // We're performing an unsigned comp with a sign extended value.
6883 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006884 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006885 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6886 NegOne, ICI.getName()), ICI);
6887 } else {
6888 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006889 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006890 }
6891 }
6892
6893 // Finally, return the value computed.
6894 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006895 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006896 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006897
6898 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6899 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6900 "ICmp should be folded!");
6901 if (Constant *CI = dyn_cast<Constant>(Result))
6902 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6903 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006904}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006905
Reid Spencer832254e2007-02-02 02:16:23 +00006906Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6907 return commonShiftTransforms(I);
6908}
6909
6910Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6911 return commonShiftTransforms(I);
6912}
6913
6914Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006915 if (Instruction *R = commonShiftTransforms(I))
6916 return R;
6917
6918 Value *Op0 = I.getOperand(0);
6919
6920 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6921 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6922 if (CSI->isAllOnesValue())
6923 return ReplaceInstUsesWith(I, CSI);
6924
6925 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006926 if (!isa<VectorType>(I.getType()) &&
6927 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006928 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006929 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006930
6931 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006932}
6933
6934Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6935 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006936 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006937
6938 // shl X, 0 == X and shr X, 0 == X
6939 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006940 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006941 Op0 == Constant::getNullValue(Op0->getType()))
6942 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006943
Reid Spencere4d87aa2006-12-23 06:05:41 +00006944 if (isa<UndefValue>(Op0)) {
6945 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006946 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006947 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6949 }
6950 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006951 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6952 return ReplaceInstUsesWith(I, Op0);
6953 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006955 }
6956
Chris Lattner2eefe512004-04-09 19:05:30 +00006957 // Try to fold constant and into select arguments.
6958 if (isa<Constant>(Op0))
6959 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006960 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006961 return R;
6962
Reid Spencerb83eb642006-10-20 07:07:24 +00006963 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006964 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6965 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006966 return 0;
6967}
6968
Reid Spencerb83eb642006-10-20 07:07:24 +00006969Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006970 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00006971 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006972
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006973 // See if we can simplify any instructions used by the instruction whose sole
6974 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006975 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00006976 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006977 return &I;
6978
Chris Lattner4d5542c2006-01-06 07:12:35 +00006979 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6980 // of a signed value.
6981 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006982 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006983 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006984 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6985 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006986 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006987 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006988 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006989 }
6990
6991 // ((X*C1) << C2) == (X * (C1 << C2))
6992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6993 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6994 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006995 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006996 ConstantExpr::getShl(BOOp, Op1));
6997
6998 // Try to fold constant and into select arguments.
6999 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7000 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7001 return R;
7002 if (isa<PHINode>(Op0))
7003 if (Instruction *NV = FoldOpIntoPhi(I))
7004 return NV;
7005
Chris Lattner8999dd32007-12-22 09:07:47 +00007006 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7007 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7008 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7009 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7010 // place. Don't try to do this transformation in this case. Also, we
7011 // require that the input operand is a shift-by-constant so that we have
7012 // confidence that the shifts will get folded together. We could do this
7013 // xform in more cases, but it is unlikely to be profitable.
7014 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7015 isa<ConstantInt>(TrOp->getOperand(1))) {
7016 // Okay, we'll do this xform. Make the shift of shift.
7017 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007018 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007019 I.getName());
7020 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7021
7022 // For logical shifts, the truncation has the effect of making the high
7023 // part of the register be zeros. Emulate this by inserting an AND to
7024 // clear the top bits as needed. This 'and' will usually be zapped by
7025 // other xforms later if dead.
7026 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7027 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7028 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7029
7030 // The mask we constructed says what the trunc would do if occurring
7031 // between the shifts. We want to know the effect *after* the second
7032 // shift. We know that it is a logical shift by a constant, so adjust the
7033 // mask as appropriate.
7034 if (I.getOpcode() == Instruction::Shl)
7035 MaskV <<= Op1->getZExtValue();
7036 else {
7037 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7038 MaskV = MaskV.lshr(Op1->getZExtValue());
7039 }
7040
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007041 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007042 TI->getName());
7043 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7044
7045 // Return the value truncated to the interesting size.
7046 return new TruncInst(And, I.getType());
7047 }
7048 }
7049
Chris Lattner4d5542c2006-01-06 07:12:35 +00007050 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007051 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7052 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7053 Value *V1, *V2;
7054 ConstantInt *CC;
7055 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007056 default: break;
7057 case Instruction::Add:
7058 case Instruction::And:
7059 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007060 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007061 // These operators commute.
7062 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007063 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007064 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007065 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007066 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007067 Op0BO->getName());
7068 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007069 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007070 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007071 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007072 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007073 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007074 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007075 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007076 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007077
Chris Lattner150f12a2005-09-18 06:30:59 +00007078 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007079 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007080 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007081 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007082 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7083 m_ConstantInt(CC))) &&
7084 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007085 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007086 Op0BO->getOperand(0), Op1,
7087 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007088 InsertNewInstBefore(YS, I); // (Y << C)
7089 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007090 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007091 V1->getName()+".mask");
7092 InsertNewInstBefore(XM, I); // X & (CC << C)
7093
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007094 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007095 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007096 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007097
Reid Spencera07cb7d2007-02-02 14:41:37 +00007098 // FALL THROUGH.
7099 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007100 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007101 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007102 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007103 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007104 Op0BO->getOperand(1), Op1,
7105 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007106 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007107 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007108 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007109 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007110 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007111 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007112 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007113 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007114 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007115
Chris Lattner13d4ab42006-05-31 21:14:00 +00007116 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007117 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7118 match(Op0BO->getOperand(0),
7119 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007120 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007121 cast<BinaryOperator>(Op0BO->getOperand(0))
7122 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007123 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007124 Op0BO->getOperand(1), Op1,
7125 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007126 InsertNewInstBefore(YS, I); // (Y << C)
7127 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007128 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007129 V1->getName()+".mask");
7130 InsertNewInstBefore(XM, I); // X & (CC << C)
7131
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007132 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007133 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007134
Chris Lattner11021cb2005-09-18 05:12:10 +00007135 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007136 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007137 }
7138
7139
7140 // If the operand is an bitwise operator with a constant RHS, and the
7141 // shift is the only use, we can pull it out of the shift.
7142 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7143 bool isValid = true; // Valid only for And, Or, Xor
7144 bool highBitSet = false; // Transform if high bit of constant set?
7145
7146 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007147 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007148 case Instruction::Add:
7149 isValid = isLeftShift;
7150 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007151 case Instruction::Or:
7152 case Instruction::Xor:
7153 highBitSet = false;
7154 break;
7155 case Instruction::And:
7156 highBitSet = true;
7157 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007158 }
7159
7160 // If this is a signed shift right, and the high bit is modified
7161 // by the logical operation, do not perform the transformation.
7162 // The highBitSet boolean indicates the value of the high bit of
7163 // the constant which would cause it to be modified for this
7164 // operation.
7165 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007166 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007167 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007168
7169 if (isValid) {
7170 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7171
7172 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007173 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007174 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007175 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007176
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007177 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007178 NewRHS);
7179 }
7180 }
7181 }
7182 }
7183
Chris Lattnerad0124c2006-01-06 07:52:12 +00007184 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007185 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7186 if (ShiftOp && !ShiftOp->isShift())
7187 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007188
Reid Spencerb83eb642006-10-20 07:07:24 +00007189 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007190 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007191 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7192 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007193 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7194 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7195 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007196
Zhou Sheng4351c642007-04-02 08:20:41 +00007197 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007198 if (AmtSum > TypeBits)
7199 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007200
7201 const IntegerType *Ty = cast<IntegerType>(I.getType());
7202
7203 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007204 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007205 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007206 ConstantInt::get(Ty, AmtSum));
7207 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7208 I.getOpcode() == Instruction::AShr) {
7209 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007210 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007211 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7212 I.getOpcode() == Instruction::LShr) {
7213 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7214 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007215 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007216 InsertNewInstBefore(Shift, I);
7217
Zhou Shenge9e03f62007-03-28 15:02:20 +00007218 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007219 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007220 }
7221
Chris Lattnerb87056f2007-02-05 00:57:54 +00007222 // Okay, if we get here, one shift must be left, and the other shift must be
7223 // right. See if the amounts are equal.
7224 if (ShiftAmt1 == ShiftAmt2) {
7225 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7226 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007227 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007228 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007229 }
7230 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7231 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007232 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007233 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007234 }
7235 // We can simplify ((X << C) >>s C) into a trunc + sext.
7236 // NOTE: we could do this for any C, but that would make 'unusual' integer
7237 // types. For now, just stick to ones well-supported by the code
7238 // generators.
7239 const Type *SExtType = 0;
7240 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007241 case 1 :
7242 case 8 :
7243 case 16 :
7244 case 32 :
7245 case 64 :
7246 case 128:
7247 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7248 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007249 default: break;
7250 }
7251 if (SExtType) {
7252 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7253 InsertNewInstBefore(NewTrunc, I);
7254 return new SExtInst(NewTrunc, Ty);
7255 }
7256 // Otherwise, we can't handle it yet.
7257 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007258 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007259
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007260 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007261 if (I.getOpcode() == Instruction::Shl) {
7262 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7263 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007264 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007265 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007266 InsertNewInstBefore(Shift, I);
7267
Reid Spencer55702aa2007-03-25 21:11:44 +00007268 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007269 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007270 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007271
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007272 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007273 if (I.getOpcode() == Instruction::LShr) {
7274 assert(ShiftOp->getOpcode() == Instruction::Shl);
7275 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007276 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007277 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007278
Reid Spencerd5e30f02007-03-26 17:18:58 +00007279 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007280 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007281 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007282
7283 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7284 } else {
7285 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007286 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007287
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007288 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007289 if (I.getOpcode() == Instruction::Shl) {
7290 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7291 ShiftOp->getOpcode() == Instruction::AShr);
7292 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007293 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007294 ConstantInt::get(Ty, ShiftDiff));
7295 InsertNewInstBefore(Shift, I);
7296
Reid Spencer55702aa2007-03-25 21:11:44 +00007297 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007298 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007299 }
7300
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007301 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007302 if (I.getOpcode() == Instruction::LShr) {
7303 assert(ShiftOp->getOpcode() == Instruction::Shl);
7304 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007305 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306 InsertNewInstBefore(Shift, I);
7307
Reid Spencer68d27cf2007-03-26 23:45:51 +00007308 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007309 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007310 }
7311
7312 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007313 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007314 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007315 return 0;
7316}
7317
Chris Lattnera1be5662002-05-02 17:06:02 +00007318
Chris Lattnercfd65102005-10-29 04:36:15 +00007319/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7320/// expression. If so, decompose it, returning some value X, such that Val is
7321/// X*Scale+Offset.
7322///
7323static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007324 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007325 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007327 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007328 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007329 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007330 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7331 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7332 if (I->getOpcode() == Instruction::Shl) {
7333 // This is a value scaled by '1 << the shift amt'.
7334 Scale = 1U << RHS->getZExtValue();
7335 Offset = 0;
7336 return I->getOperand(0);
7337 } else if (I->getOpcode() == Instruction::Mul) {
7338 // This value is scaled by 'RHS'.
7339 Scale = RHS->getZExtValue();
7340 Offset = 0;
7341 return I->getOperand(0);
7342 } else if (I->getOpcode() == Instruction::Add) {
7343 // We have X+C. Check to see if we really have (X*C2)+C1,
7344 // where C1 is divisible by C2.
7345 unsigned SubScale;
7346 Value *SubVal =
7347 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7348 Offset += RHS->getZExtValue();
7349 Scale = SubScale;
7350 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007351 }
7352 }
7353 }
7354
7355 // Otherwise, we can't look past this.
7356 Scale = 1;
7357 Offset = 0;
7358 return Val;
7359}
7360
7361
Chris Lattnerb3f83972005-10-24 06:03:58 +00007362/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7363/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007364Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007365 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007366 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007367
Chris Lattnerb53c2382005-10-24 06:22:12 +00007368 // Remove any uses of AI that are dead.
7369 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007370
Chris Lattnerb53c2382005-10-24 06:22:12 +00007371 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7372 Instruction *User = cast<Instruction>(*UI++);
7373 if (isInstructionTriviallyDead(User)) {
7374 while (UI != E && *UI == User)
7375 ++UI; // If this instruction uses AI more than once, don't break UI.
7376
Chris Lattnerb53c2382005-10-24 06:22:12 +00007377 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007378 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007379 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007380 }
7381 }
7382
Chris Lattnerb3f83972005-10-24 06:03:58 +00007383 // Get the type really allocated and the type casted to.
7384 const Type *AllocElTy = AI.getAllocatedType();
7385 const Type *CastElTy = PTy->getElementType();
7386 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007387
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007388 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7389 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007390 if (CastElTyAlign < AllocElTyAlign) return 0;
7391
Chris Lattner39387a52005-10-24 06:35:18 +00007392 // If the allocation has multiple uses, only promote it if we are strictly
7393 // increasing the alignment of the resultant allocation. If we keep it the
7394 // same, we open the door to infinite loops of various kinds.
7395 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7396
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007397 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7398 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007399 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007400
Chris Lattner455fcc82005-10-29 03:19:53 +00007401 // See if we can satisfy the modulus by pulling a scale out of the array
7402 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007403 unsigned ArraySizeScale;
7404 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007405 Value *NumElements = // See if the array size is a decomposable linear expr.
7406 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7407
Chris Lattner455fcc82005-10-29 03:19:53 +00007408 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7409 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007410 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7411 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007412
Chris Lattner455fcc82005-10-29 03:19:53 +00007413 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7414 Value *Amt = 0;
7415 if (Scale == 1) {
7416 Amt = NumElements;
7417 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007418 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007419 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7420 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007421 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007422 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007423 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007424 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007425 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007426 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007427 }
7428
Jeff Cohen86796be2007-04-04 16:58:57 +00007429 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7430 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007431 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007432 Amt = InsertNewInstBefore(Tmp, AI);
7433 }
7434
Chris Lattnerb3f83972005-10-24 06:03:58 +00007435 AllocationInst *New;
7436 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007437 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007438 else
Chris Lattner6934a042007-02-11 01:23:03 +00007439 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007440 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007441 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007442
7443 // If the allocation has multiple uses, insert a cast and change all things
7444 // that used it to use the new cast. This will also hack on CI, but it will
7445 // die soon.
7446 if (!AI.hasOneUse()) {
7447 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007448 // New is the allocation instruction, pointer typed. AI is the original
7449 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7450 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007451 InsertNewInstBefore(NewCast, AI);
7452 AI.replaceAllUsesWith(NewCast);
7453 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007454 return ReplaceInstUsesWith(CI, New);
7455}
7456
Chris Lattner70074e02006-05-13 02:06:03 +00007457/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007458/// and return it as type Ty without inserting any new casts and without
7459/// changing the computed value. This is used by code that tries to decide
7460/// whether promoting or shrinking integer operations to wider or smaller types
7461/// will allow us to eliminate a truncate or extend.
7462///
7463/// This is a truncation operation if Ty is smaller than V->getType(), or an
7464/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007465///
7466/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7467/// should return true if trunc(V) can be computed by computing V in the smaller
7468/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7469/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7470/// efficiently truncated.
7471///
7472/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7473/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7474/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007475bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7476 unsigned CastOpc,
7477 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007478 // We can always evaluate constants in another type.
7479 if (isa<ConstantInt>(V))
7480 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007481
7482 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007483 if (!I) return false;
7484
7485 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007486
Chris Lattner951626b2007-08-02 06:11:14 +00007487 // If this is an extension or truncate, we can often eliminate it.
7488 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7489 // If this is a cast from the destination type, we can trivially eliminate
7490 // it, and this will remove a cast overall.
7491 if (I->getOperand(0)->getType() == Ty) {
7492 // If the first operand is itself a cast, and is eliminable, do not count
7493 // this as an eliminable cast. We would prefer to eliminate those two
7494 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007495 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007496 ++NumCastsRemoved;
7497 return true;
7498 }
7499 }
7500
7501 // We can't extend or shrink something that has multiple uses: doing so would
7502 // require duplicating the instruction in general, which isn't profitable.
7503 if (!I->hasOneUse()) return false;
7504
Evan Chengf35fd542009-01-15 17:01:23 +00007505 unsigned Opc = I->getOpcode();
7506 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007507 case Instruction::Add:
7508 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007509 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007510 case Instruction::And:
7511 case Instruction::Or:
7512 case Instruction::Xor:
7513 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007514 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007515 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007516 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007517 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007518
Chris Lattner46b96052006-11-29 07:18:39 +00007519 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007520 // If we are truncating the result of this SHL, and if it's a shift of a
7521 // constant amount, we can always perform a SHL in a smaller type.
7522 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007523 uint32_t BitWidth = Ty->getBitWidth();
7524 if (BitWidth < OrigTy->getBitWidth() &&
7525 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007526 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007527 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007528 }
7529 break;
7530 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007531 // If this is a truncate of a logical shr, we can truncate it to a smaller
7532 // lshr iff we know that the bits we would otherwise be shifting in are
7533 // already zeros.
7534 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007535 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7536 uint32_t BitWidth = Ty->getBitWidth();
7537 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007538 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007539 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7540 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007541 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007542 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007543 }
7544 }
Chris Lattner46b96052006-11-29 07:18:39 +00007545 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007546 case Instruction::ZExt:
7547 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007548 case Instruction::Trunc:
7549 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007550 // can safely replace it. Note that replacing it does not reduce the number
7551 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007552 if (Opc == CastOpc)
7553 return true;
7554
7555 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007556 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007557 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007558 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007559 case Instruction::Select: {
7560 SelectInst *SI = cast<SelectInst>(I);
7561 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007562 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007563 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007564 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007565 }
Chris Lattner8114b712008-06-18 04:00:49 +00007566 case Instruction::PHI: {
7567 // We can change a phi if we can change all operands.
7568 PHINode *PN = cast<PHINode>(I);
7569 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7570 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007571 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007572 return false;
7573 return true;
7574 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007575 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007576 // TODO: Can handle more cases here.
7577 break;
7578 }
7579
7580 return false;
7581}
7582
7583/// EvaluateInDifferentType - Given an expression that
7584/// CanEvaluateInDifferentType returns true for, actually insert the code to
7585/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007586Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007587 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007588 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007589 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007590
7591 // Otherwise, it must be an instruction.
7592 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007593 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007594 unsigned Opc = I->getOpcode();
7595 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007596 case Instruction::Add:
7597 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007598 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007599 case Instruction::And:
7600 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007601 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007602 case Instruction::AShr:
7603 case Instruction::LShr:
7604 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007605 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007606 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007607 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007608 break;
7609 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007610 case Instruction::Trunc:
7611 case Instruction::ZExt:
7612 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007613 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007614 // just return the source. There's no need to insert it because it is not
7615 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007616 if (I->getOperand(0)->getType() == Ty)
7617 return I->getOperand(0);
7618
Chris Lattner8114b712008-06-18 04:00:49 +00007619 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007620 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007621 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007622 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007623 case Instruction::Select: {
7624 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7625 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7626 Res = SelectInst::Create(I->getOperand(0), True, False);
7627 break;
7628 }
Chris Lattner8114b712008-06-18 04:00:49 +00007629 case Instruction::PHI: {
7630 PHINode *OPN = cast<PHINode>(I);
7631 PHINode *NPN = PHINode::Create(Ty);
7632 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7633 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7634 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7635 }
7636 Res = NPN;
7637 break;
7638 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007639 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007640 // TODO: Can handle more cases here.
7641 assert(0 && "Unreachable!");
7642 break;
7643 }
7644
Chris Lattner8114b712008-06-18 04:00:49 +00007645 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007646 return InsertNewInstBefore(Res, *I);
7647}
7648
Reid Spencer3da59db2006-11-27 01:05:10 +00007649/// @brief Implement the transforms common to all CastInst visitors.
7650Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007651 Value *Src = CI.getOperand(0);
7652
Dan Gohman23d9d272007-05-11 21:10:54 +00007653 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007654 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007655 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007656 if (Instruction::CastOps opc =
7657 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7658 // The first cast (CSrc) is eliminable so we need to fix up or replace
7659 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007660 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007661 }
7662 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007663
Reid Spencer3da59db2006-11-27 01:05:10 +00007664 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007665 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7666 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7667 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007668
7669 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007670 if (isa<PHINode>(Src))
7671 if (Instruction *NV = FoldOpIntoPhi(CI))
7672 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007673
Reid Spencer3da59db2006-11-27 01:05:10 +00007674 return 0;
7675}
7676
Chris Lattner46cd5a12009-01-09 05:44:56 +00007677/// FindElementAtOffset - Given a type and a constant offset, determine whether
7678/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007679/// the specified offset. If so, fill them into NewIndices and return the
7680/// resultant element type, otherwise return null.
7681static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7682 SmallVectorImpl<Value*> &NewIndices,
7683 const TargetData *TD) {
7684 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007685
7686 // Start with the index over the outer type. Note that the type size
7687 // might be zero (even if the offset isn't zero) if the indexed type
7688 // is something like [0 x {int, int}]
7689 const Type *IntPtrTy = TD->getIntPtrType();
7690 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007691 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007692 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007693 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007694
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007695 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007696 if (Offset < 0) {
7697 --FirstIdx;
7698 Offset += TySize;
7699 assert(Offset >= 0);
7700 }
7701 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7702 }
7703
7704 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7705
7706 // Index into the types. If we fail, set OrigBase to null.
7707 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007708 // Indexing into tail padding between struct/array elements.
7709 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007710 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007711
Chris Lattner46cd5a12009-01-09 05:44:56 +00007712 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7713 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007714 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7715 "Offset must stay within the indexed type");
7716
Chris Lattner46cd5a12009-01-09 05:44:56 +00007717 unsigned Elt = SL->getElementContainingOffset(Offset);
7718 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7719
7720 Offset -= SL->getElementOffset(Elt);
7721 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007722 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007723 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007724 assert(EltSize && "Cannot index into a zero-sized array");
7725 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7726 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007727 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007728 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007729 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007730 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007731 }
7732 }
7733
Chris Lattner3914f722009-01-24 01:00:13 +00007734 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007735}
7736
Chris Lattnerd3e28342007-04-27 17:44:50 +00007737/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7738Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7739 Value *Src = CI.getOperand(0);
7740
Chris Lattnerd3e28342007-04-27 17:44:50 +00007741 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007742 // If casting the result of a getelementptr instruction with no offset, turn
7743 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007744 if (GEP->hasAllZeroIndices()) {
7745 // Changing the cast operand is usually not a good idea but it is safe
7746 // here because the pointer operand is being replaced with another
7747 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007748 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007749 CI.setOperand(0, GEP->getOperand(0));
7750 return &CI;
7751 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007752
7753 // If the GEP has a single use, and the base pointer is a bitcast, and the
7754 // GEP computes a constant offset, see if we can convert these three
7755 // instructions into fewer. This typically happens with unions and other
7756 // non-type-safe code.
7757 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7758 if (GEP->hasAllConstantIndices()) {
7759 // We are guaranteed to get a constant from EmitGEPOffset.
7760 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7761 int64_t Offset = OffsetV->getSExtValue();
7762
7763 // Get the base pointer input of the bitcast, and the type it points to.
7764 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7765 const Type *GEPIdxTy =
7766 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007767 SmallVector<Value*, 8> NewIndices;
7768 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7769 // If we were able to index down into an element, create the GEP
7770 // and bitcast the result. This eliminates one bitcast, potentially
7771 // two.
7772 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7773 NewIndices.begin(),
7774 NewIndices.end(), "");
7775 InsertNewInstBefore(NGEP, CI);
7776 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007777
Chris Lattner46cd5a12009-01-09 05:44:56 +00007778 if (isa<BitCastInst>(CI))
7779 return new BitCastInst(NGEP, CI.getType());
7780 assert(isa<PtrToIntInst>(CI));
7781 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007782 }
7783 }
7784 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007785 }
7786
7787 return commonCastTransforms(CI);
7788}
7789
7790
Chris Lattnerc739cd62007-03-03 05:27:34 +00007791/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7792/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007793/// cases.
7794/// @brief Implement the transforms common to CastInst with integer operands
7795Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7796 if (Instruction *Result = commonCastTransforms(CI))
7797 return Result;
7798
7799 Value *Src = CI.getOperand(0);
7800 const Type *SrcTy = Src->getType();
7801 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007802 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7803 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007804
Reid Spencer3da59db2006-11-27 01:05:10 +00007805 // See if we can simplify any instructions used by the LHS whose sole
7806 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007807 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007808 return &CI;
7809
7810 // If the source isn't an instruction or has more than one use then we
7811 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007812 Instruction *SrcI = dyn_cast<Instruction>(Src);
7813 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007814 return 0;
7815
Chris Lattnerc739cd62007-03-03 05:27:34 +00007816 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007817 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007818 if (!isa<BitCastInst>(CI) &&
7819 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007820 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007821 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007822 // eliminates the cast, so it is always a win. If this is a zero-extension,
7823 // we need to do an AND to maintain the clear top-part of the computation,
7824 // so we require that the input have eliminated at least one cast. If this
7825 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007826 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007827 bool DoXForm = false;
7828 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007829 switch (CI.getOpcode()) {
7830 default:
7831 // All the others use floating point so we shouldn't actually
7832 // get here because of the check above.
7833 assert(0 && "Unknown cast type");
7834 case Instruction::Trunc:
7835 DoXForm = true;
7836 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007837 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007838 DoXForm = NumCastsRemoved >= 1;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007839 if (!DoXForm) {
7840 // If it's unnecessary to issue an AND to clear the high bits, it's
7841 // always profitable to do this xform.
7842 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7843 CI.getOpcode() == Instruction::SExt);
7844 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7845 if (MaskedValueIsZero(TryRes, Mask))
7846 return ReplaceInstUsesWith(CI, TryRes);
7847 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7848 if (TryI->use_empty())
7849 EraseInstFromFunction(*TryI);
7850 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007851 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007852 }
Evan Chengf35fd542009-01-15 17:01:23 +00007853 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007854 DoXForm = NumCastsRemoved >= 2;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007855 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7856 // If we do not have to emit the truncate + sext pair, then it's always
7857 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007858 //
7859 // It's not safe to eliminate the trunc + sext pair if one of the
7860 // eliminated cast is a truncate. e.g.
7861 // t2 = trunc i32 t1 to i16
7862 // t3 = sext i16 t2 to i32
7863 // !=
7864 // i32 t1
Evan Cheng4e56ab22009-01-16 02:11:43 +00007865 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7866 CI.getOpcode() == Instruction::SExt);
7867 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7868 if (NumSignBits > (DestBitSize - SrcBitSize))
7869 return ReplaceInstUsesWith(CI, TryRes);
7870 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7871 if (TryI->use_empty())
7872 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007873 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007874 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007875 }
Evan Chengf35fd542009-01-15 17:01:23 +00007876 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007877
7878 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007879 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7880 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007881 if (JustReplace)
7882 // Just replace this cast with the result.
7883 return ReplaceInstUsesWith(CI, Res);
7884
Reid Spencer3da59db2006-11-27 01:05:10 +00007885 assert(Res->getType() == DestTy);
7886 switch (CI.getOpcode()) {
7887 default: assert(0 && "Unknown cast type!");
7888 case Instruction::Trunc:
7889 case Instruction::BitCast:
7890 // Just replace this cast with the result.
7891 return ReplaceInstUsesWith(CI, Res);
7892 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007893 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007894
7895 // If the high bits are already zero, just replace this cast with the
7896 // result.
7897 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7898 if (MaskedValueIsZero(Res, Mask))
7899 return ReplaceInstUsesWith(CI, Res);
7900
7901 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007902 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7903 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007904 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007905 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007906 case Instruction::SExt: {
7907 // If the high bits are already filled with sign bit, just replace this
7908 // cast with the result.
7909 unsigned NumSignBits = ComputeNumSignBits(Res);
7910 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00007911 return ReplaceInstUsesWith(CI, Res);
7912
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007914 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007915 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7916 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007917 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007918 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007919 }
7920 }
7921
7922 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7923 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7924
7925 switch (SrcI->getOpcode()) {
7926 case Instruction::Add:
7927 case Instruction::Mul:
7928 case Instruction::And:
7929 case Instruction::Or:
7930 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007931 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007932 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7933 // Don't insert two casts if they cannot be eliminated. We allow
7934 // two casts to be inserted if the sizes are the same. This could
7935 // only be converting signedness, which is a noop.
7936 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007937 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7938 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007939 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007940 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7941 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007942 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007943 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007944 }
7945 }
7946
7947 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7948 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7949 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007950 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007951 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007952 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007953 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007954 }
7955 break;
7956 case Instruction::SDiv:
7957 case Instruction::UDiv:
7958 case Instruction::SRem:
7959 case Instruction::URem:
7960 // If we are just changing the sign, rewrite.
7961 if (DestBitSize == SrcBitSize) {
7962 // Don't insert two casts if they cannot be eliminated. We allow
7963 // two casts to be inserted if the sizes are the same. This could
7964 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007965 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7966 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007967 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7968 Op0, DestTy, *SrcI);
7969 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7970 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007971 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007972 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7973 }
7974 }
7975 break;
7976
7977 case Instruction::Shl:
7978 // Allow changing the sign of the source operand. Do not allow
7979 // changing the size of the shift, UNLESS the shift amount is a
7980 // constant. We must not change variable sized shifts to a smaller
7981 // size, because it is undefined to shift more bits out than exist
7982 // in the value.
7983 if (DestBitSize == SrcBitSize ||
7984 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007985 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7986 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007987 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7988 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007989 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 }
7991 break;
7992 case Instruction::AShr:
7993 // If this is a signed shr, and if all bits shifted in are about to be
7994 // truncated off, turn it into an unsigned shr to allow greater
7995 // simplifications.
7996 if (DestBitSize < SrcBitSize &&
7997 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007998 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007999 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8000 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008001 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 }
8003 }
8004 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008005 }
8006 return 0;
8007}
8008
Chris Lattner8a9f5712007-04-11 06:57:46 +00008009Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008010 if (Instruction *Result = commonIntCastTransforms(CI))
8011 return Result;
8012
8013 Value *Src = CI.getOperand(0);
8014 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008015 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8016 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008017
8018 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8019 switch (SrcI->getOpcode()) {
8020 default: break;
8021 case Instruction::LShr:
8022 // We can shrink lshr to something smaller if we know the bits shifted in
8023 // are already zeros.
8024 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008025 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008026
8027 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008028 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008029 Value* SrcIOp0 = SrcI->getOperand(0);
8030 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008031 if (ShAmt >= DestBitWidth) // All zeros.
8032 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8033
8034 // Okay, we can shrink this. Truncate the input, then return a new
8035 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008036 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8037 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8038 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008039 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008040 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008041 } else { // This is a variable shr.
8042
8043 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8044 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8045 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008046 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008047 Value *One = ConstantInt::get(SrcI->getType(), 1);
8048
Reid Spencer832254e2007-02-02 02:16:23 +00008049 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008050 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008051 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008052 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008053 SrcI->getOperand(0),
8054 "tmp"), CI);
8055 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008056 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008057 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008058 }
8059 break;
8060 }
8061 }
8062
8063 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008064}
8065
Evan Chengb98a10e2008-03-24 00:21:34 +00008066/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8067/// in order to eliminate the icmp.
8068Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8069 bool DoXform) {
8070 // If we are just checking for a icmp eq of a single bit and zext'ing it
8071 // to an integer, then shift the bit to the appropriate place and then
8072 // cast to integer to avoid the comparison.
8073 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8074 const APInt &Op1CV = Op1C->getValue();
8075
8076 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8077 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8078 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8079 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8080 if (!DoXform) return ICI;
8081
8082 Value *In = ICI->getOperand(0);
8083 Value *Sh = ConstantInt::get(In->getType(),
8084 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008085 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008086 In->getName()+".lobit"),
8087 CI);
8088 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008089 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008090 false/*ZExt*/, "tmp", &CI);
8091
8092 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8093 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008094 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008095 In->getName()+".not"),
8096 CI);
8097 }
8098
8099 return ReplaceInstUsesWith(CI, In);
8100 }
8101
8102
8103
8104 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8105 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8106 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8107 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8108 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8109 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8110 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8111 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8112 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8113 // This only works for EQ and NE
8114 ICI->isEquality()) {
8115 // If Op1C some other power of two, convert:
8116 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8117 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8118 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8119 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8120
8121 APInt KnownZeroMask(~KnownZero);
8122 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8123 if (!DoXform) return ICI;
8124
8125 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8126 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8127 // (X&4) == 2 --> false
8128 // (X&4) != 2 --> true
8129 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8130 Res = ConstantExpr::getZExt(Res, CI.getType());
8131 return ReplaceInstUsesWith(CI, Res);
8132 }
8133
8134 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8135 Value *In = ICI->getOperand(0);
8136 if (ShiftAmt) {
8137 // Perform a logical shr by shiftamt.
8138 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008139 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008140 ConstantInt::get(In->getType(), ShiftAmt),
8141 In->getName()+".lobit"), CI);
8142 }
8143
8144 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8145 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008146 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008147 InsertNewInstBefore(cast<Instruction>(In), CI);
8148 }
8149
8150 if (CI.getType() == In->getType())
8151 return ReplaceInstUsesWith(CI, In);
8152 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008153 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008154 }
8155 }
8156 }
8157
8158 return 0;
8159}
8160
Chris Lattner8a9f5712007-04-11 06:57:46 +00008161Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008162 // If one of the common conversion will work ..
8163 if (Instruction *Result = commonIntCastTransforms(CI))
8164 return Result;
8165
8166 Value *Src = CI.getOperand(0);
8167
8168 // If this is a cast of a cast
8169 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008170 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8171 // types and if the sizes are just right we can convert this into a logical
8172 // 'and' which will be much cheaper than the pair of casts.
8173 if (isa<TruncInst>(CSrc)) {
8174 // Get the sizes of the types involved
8175 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008176 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8177 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8178 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008179 // If we're actually extending zero bits and the trunc is a no-op
8180 if (MidSize < DstSize && SrcSize == DstSize) {
8181 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008182 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008183 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008184 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008185 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008186 // Unfortunately, if the type changed, we need to cast it back.
8187 if (And->getType() != CI.getType()) {
8188 And->setName(CSrc->getName()+".mask");
8189 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008190 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008191 }
8192 return And;
8193 }
8194 }
8195 }
8196
Evan Chengb98a10e2008-03-24 00:21:34 +00008197 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8198 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008199
Evan Chengb98a10e2008-03-24 00:21:34 +00008200 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8201 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8202 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8203 // of the (zext icmp) will be transformed.
8204 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8205 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8206 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8207 (transformZExtICmp(LHS, CI, false) ||
8208 transformZExtICmp(RHS, CI, false))) {
8209 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8210 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008211 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008212 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008213 }
8214
Reid Spencer3da59db2006-11-27 01:05:10 +00008215 return 0;
8216}
8217
Chris Lattner8a9f5712007-04-11 06:57:46 +00008218Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008219 if (Instruction *I = commonIntCastTransforms(CI))
8220 return I;
8221
Chris Lattner8a9f5712007-04-11 06:57:46 +00008222 Value *Src = CI.getOperand(0);
8223
Dan Gohman1975d032008-10-30 20:40:10 +00008224 // Canonicalize sign-extend from i1 to a select.
8225 if (Src->getType() == Type::Int1Ty)
8226 return SelectInst::Create(Src,
8227 ConstantInt::getAllOnesValue(CI.getType()),
8228 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008229
8230 // See if the value being truncated is already sign extended. If so, just
8231 // eliminate the trunc/sext pair.
8232 if (getOpcode(Src) == Instruction::Trunc) {
8233 Value *Op = cast<User>(Src)->getOperand(0);
8234 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8235 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8236 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8237 unsigned NumSignBits = ComputeNumSignBits(Op);
8238
8239 if (OpBits == DestBits) {
8240 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8241 // bits, it is already ready.
8242 if (NumSignBits > DestBits-MidBits)
8243 return ReplaceInstUsesWith(CI, Op);
8244 } else if (OpBits < DestBits) {
8245 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8246 // bits, just sext from i32.
8247 if (NumSignBits > OpBits-MidBits)
8248 return new SExtInst(Op, CI.getType(), "tmp");
8249 } else {
8250 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8251 // bits, just truncate to i32.
8252 if (NumSignBits > OpBits-MidBits)
8253 return new TruncInst(Op, CI.getType(), "tmp");
8254 }
8255 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008256
8257 // If the input is a shl/ashr pair of a same constant, then this is a sign
8258 // extension from a smaller value. If we could trust arbitrary bitwidth
8259 // integers, we could turn this into a truncate to the smaller bit and then
8260 // use a sext for the whole extension. Since we don't, look deeper and check
8261 // for a truncate. If the source and dest are the same type, eliminate the
8262 // trunc and extend and just do shifts. For example, turn:
8263 // %a = trunc i32 %i to i8
8264 // %b = shl i8 %a, 6
8265 // %c = ashr i8 %b, 6
8266 // %d = sext i8 %c to i32
8267 // into:
8268 // %a = shl i32 %i, 30
8269 // %d = ashr i32 %a, 30
8270 Value *A = 0;
8271 ConstantInt *BA = 0, *CA = 0;
8272 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8273 m_ConstantInt(CA))) &&
8274 BA == CA && isa<TruncInst>(A)) {
8275 Value *I = cast<TruncInst>(A)->getOperand(0);
8276 if (I->getType() == CI.getType()) {
8277 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8278 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8279 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8280 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8281 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8282 CI.getName()), CI);
8283 return BinaryOperator::CreateAShr(I, ShAmtV);
8284 }
8285 }
8286
Chris Lattnerba417832007-04-11 06:12:58 +00008287 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008288}
8289
Chris Lattnerb7530652008-01-27 05:29:54 +00008290/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8291/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008292static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008293 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008294 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008295 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8296 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008297 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008298 return 0;
8299}
8300
8301/// LookThroughFPExtensions - If this is an fp extension instruction, look
8302/// through it until we get the source value.
8303static Value *LookThroughFPExtensions(Value *V) {
8304 if (Instruction *I = dyn_cast<Instruction>(V))
8305 if (I->getOpcode() == Instruction::FPExt)
8306 return LookThroughFPExtensions(I->getOperand(0));
8307
8308 // If this value is a constant, return the constant in the smallest FP type
8309 // that can accurately represent it. This allows us to turn
8310 // (float)((double)X+2.0) into x+2.0f.
8311 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8312 if (CFP->getType() == Type::PPC_FP128Ty)
8313 return V; // No constant folding of this.
8314 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008315 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008316 return V;
8317 if (CFP->getType() == Type::DoubleTy)
8318 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008319 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008320 return V;
8321 // Don't try to shrink to various long double types.
8322 }
8323
8324 return V;
8325}
8326
8327Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8328 if (Instruction *I = commonCastTransforms(CI))
8329 return I;
8330
8331 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8332 // smaller than the destination type, we can eliminate the truncate by doing
8333 // the add as the smaller type. This applies to add/sub/mul/div as well as
8334 // many builtins (sqrt, etc).
8335 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8336 if (OpI && OpI->hasOneUse()) {
8337 switch (OpI->getOpcode()) {
8338 default: break;
8339 case Instruction::Add:
8340 case Instruction::Sub:
8341 case Instruction::Mul:
8342 case Instruction::FDiv:
8343 case Instruction::FRem:
8344 const Type *SrcTy = OpI->getType();
8345 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8346 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8347 if (LHSTrunc->getType() != SrcTy &&
8348 RHSTrunc->getType() != SrcTy) {
8349 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8350 // If the source types were both smaller than the destination type of
8351 // the cast, do this xform.
8352 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8353 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8354 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8355 CI.getType(), CI);
8356 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8357 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008358 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008359 }
8360 }
8361 break;
8362 }
8363 }
8364 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008365}
8366
8367Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8368 return commonCastTransforms(CI);
8369}
8370
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008371Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008372 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8373 if (OpI == 0)
8374 return commonCastTransforms(FI);
8375
8376 // fptoui(uitofp(X)) --> X
8377 // fptoui(sitofp(X)) --> X
8378 // This is safe if the intermediate type has enough bits in its mantissa to
8379 // accurately represent all values of X. For example, do not do this with
8380 // i64->float->i64. This is also safe for sitofp case, because any negative
8381 // 'X' value would cause an undefined result for the fptoui.
8382 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8383 OpI->getOperand(0)->getType() == FI.getType() &&
8384 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8385 OpI->getType()->getFPMantissaWidth())
8386 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008387
8388 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008389}
8390
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008391Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008392 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8393 if (OpI == 0)
8394 return commonCastTransforms(FI);
8395
8396 // fptosi(sitofp(X)) --> X
8397 // fptosi(uitofp(X)) --> X
8398 // This is safe if the intermediate type has enough bits in its mantissa to
8399 // accurately represent all values of X. For example, do not do this with
8400 // i64->float->i64. This is also safe for sitofp case, because any negative
8401 // 'X' value would cause an undefined result for the fptoui.
8402 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8403 OpI->getOperand(0)->getType() == FI.getType() &&
8404 (int)FI.getType()->getPrimitiveSizeInBits() <=
8405 OpI->getType()->getFPMantissaWidth())
8406 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008407
8408 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008409}
8410
8411Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8412 return commonCastTransforms(CI);
8413}
8414
8415Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8416 return commonCastTransforms(CI);
8417}
8418
8419Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008420 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008421}
8422
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008423Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8424 if (Instruction *I = commonCastTransforms(CI))
8425 return I;
8426
8427 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8428 if (!DestPointee->isSized()) return 0;
8429
8430 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8431 ConstantInt *Cst;
8432 Value *X;
8433 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8434 m_ConstantInt(Cst)))) {
8435 // If the source and destination operands have the same type, see if this
8436 // is a single-index GEP.
8437 if (X->getType() == CI.getType()) {
8438 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008439 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008440
8441 // Convert the constant to intptr type.
8442 APInt Offset = Cst->getValue();
8443 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8444
8445 // If Offset is evenly divisible by Size, we can do this xform.
8446 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8447 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008448 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008449 }
8450 }
8451 // TODO: Could handle other cases, e.g. where add is indexing into field of
8452 // struct etc.
8453 } else if (CI.getOperand(0)->hasOneUse() &&
8454 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8455 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8456 // "inttoptr+GEP" instead of "add+intptr".
8457
8458 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008459 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008460
8461 // Convert the constant to intptr type.
8462 APInt Offset = Cst->getValue();
8463 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8464
8465 // If Offset is evenly divisible by Size, we can do this xform.
8466 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8467 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8468
8469 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8470 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008471 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008472 }
8473 }
8474 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008475}
8476
Chris Lattnerd3e28342007-04-27 17:44:50 +00008477Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008478 // If the operands are integer typed then apply the integer transforms,
8479 // otherwise just apply the common ones.
8480 Value *Src = CI.getOperand(0);
8481 const Type *SrcTy = Src->getType();
8482 const Type *DestTy = CI.getType();
8483
Chris Lattner42a75512007-01-15 02:27:26 +00008484 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008485 if (Instruction *Result = commonIntCastTransforms(CI))
8486 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008487 } else if (isa<PointerType>(SrcTy)) {
8488 if (Instruction *I = commonPointerCastTransforms(CI))
8489 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008490 } else {
8491 if (Instruction *Result = commonCastTransforms(CI))
8492 return Result;
8493 }
8494
8495
8496 // Get rid of casts from one type to the same type. These are useless and can
8497 // be replaced by the operand.
8498 if (DestTy == Src->getType())
8499 return ReplaceInstUsesWith(CI, Src);
8500
Reid Spencer3da59db2006-11-27 01:05:10 +00008501 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008502 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8503 const Type *DstElTy = DstPTy->getElementType();
8504 const Type *SrcElTy = SrcPTy->getElementType();
8505
Nate Begeman83ad90a2008-03-31 00:22:16 +00008506 // If the address spaces don't match, don't eliminate the bitcast, which is
8507 // required for changing types.
8508 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8509 return 0;
8510
Chris Lattnerd3e28342007-04-27 17:44:50 +00008511 // If we are casting a malloc or alloca to a pointer to a type of the same
8512 // size, rewrite the allocation instruction to allocate the "right" type.
8513 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8514 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8515 return V;
8516
Chris Lattnerd717c182007-05-05 22:32:24 +00008517 // If the source and destination are pointers, and this cast is equivalent
8518 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008519 // This can enhance SROA and other transforms that want type-safe pointers.
8520 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8521 unsigned NumZeros = 0;
8522 while (SrcElTy != DstElTy &&
8523 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8524 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8525 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8526 ++NumZeros;
8527 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008528
Chris Lattnerd3e28342007-04-27 17:44:50 +00008529 // If we found a path from the src to dest, create the getelementptr now.
8530 if (SrcElTy == DstElTy) {
8531 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008532 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8533 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008534 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008536
Reid Spencer3da59db2006-11-27 01:05:10 +00008537 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8538 if (SVI->hasOneUse()) {
8539 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8540 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008541 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008542 cast<VectorType>(DestTy)->getNumElements() ==
8543 SVI->getType()->getNumElements() &&
8544 SVI->getType()->getNumElements() ==
8545 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008546 CastInst *Tmp;
8547 // If either of the operands is a cast from CI.getType(), then
8548 // evaluating the shuffle in the casted destination's type will allow
8549 // us to eliminate at least one cast.
8550 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8551 Tmp->getOperand(0)->getType() == DestTy) ||
8552 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8553 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008554 Value *LHS = InsertCastBefore(Instruction::BitCast,
8555 SVI->getOperand(0), DestTy, CI);
8556 Value *RHS = InsertCastBefore(Instruction::BitCast,
8557 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008558 // Return a new shuffle vector. Use the same element ID's, as we
8559 // know the vector types match #elts.
8560 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008561 }
8562 }
8563 }
8564 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008565 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008566}
8567
Chris Lattnere576b912004-04-09 23:46:01 +00008568/// GetSelectFoldableOperands - We want to turn code that looks like this:
8569/// %C = or %A, %B
8570/// %D = select %cond, %C, %A
8571/// into:
8572/// %C = select %cond, %B, 0
8573/// %D = or %A, %C
8574///
8575/// Assuming that the specified instruction is an operand to the select, return
8576/// a bitmask indicating which operands of this instruction are foldable if they
8577/// equal the other incoming value of the select.
8578///
8579static unsigned GetSelectFoldableOperands(Instruction *I) {
8580 switch (I->getOpcode()) {
8581 case Instruction::Add:
8582 case Instruction::Mul:
8583 case Instruction::And:
8584 case Instruction::Or:
8585 case Instruction::Xor:
8586 return 3; // Can fold through either operand.
8587 case Instruction::Sub: // Can only fold on the amount subtracted.
8588 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008589 case Instruction::LShr:
8590 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008591 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008592 default:
8593 return 0; // Cannot fold
8594 }
8595}
8596
8597/// GetSelectFoldableConstant - For the same transformation as the previous
8598/// function, return the identity constant that goes into the select.
8599static Constant *GetSelectFoldableConstant(Instruction *I) {
8600 switch (I->getOpcode()) {
8601 default: assert(0 && "This cannot happen!"); abort();
8602 case Instruction::Add:
8603 case Instruction::Sub:
8604 case Instruction::Or:
8605 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008606 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008607 case Instruction::LShr:
8608 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008609 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008610 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008611 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008612 case Instruction::Mul:
8613 return ConstantInt::get(I->getType(), 1);
8614 }
8615}
8616
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008617/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8618/// have the same opcode and only one use each. Try to simplify this.
8619Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8620 Instruction *FI) {
8621 if (TI->getNumOperands() == 1) {
8622 // If this is a non-volatile load or a cast from the same type,
8623 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008624 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008625 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8626 return 0;
8627 } else {
8628 return 0; // unknown unary op.
8629 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008630
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008631 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008632 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8633 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008634 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008635 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008636 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008637 }
8638
Reid Spencer832254e2007-02-02 02:16:23 +00008639 // Only handle binary operators here.
8640 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008641 return 0;
8642
8643 // Figure out if the operations have any operands in common.
8644 Value *MatchOp, *OtherOpT, *OtherOpF;
8645 bool MatchIsOpZero;
8646 if (TI->getOperand(0) == FI->getOperand(0)) {
8647 MatchOp = TI->getOperand(0);
8648 OtherOpT = TI->getOperand(1);
8649 OtherOpF = FI->getOperand(1);
8650 MatchIsOpZero = true;
8651 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8652 MatchOp = TI->getOperand(1);
8653 OtherOpT = TI->getOperand(0);
8654 OtherOpF = FI->getOperand(0);
8655 MatchIsOpZero = false;
8656 } else if (!TI->isCommutative()) {
8657 return 0;
8658 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8659 MatchOp = TI->getOperand(0);
8660 OtherOpT = TI->getOperand(1);
8661 OtherOpF = FI->getOperand(0);
8662 MatchIsOpZero = true;
8663 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8664 MatchOp = TI->getOperand(1);
8665 OtherOpT = TI->getOperand(0);
8666 OtherOpF = FI->getOperand(1);
8667 MatchIsOpZero = true;
8668 } else {
8669 return 0;
8670 }
8671
8672 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008673 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8674 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008675 InsertNewInstBefore(NewSI, SI);
8676
8677 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8678 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008679 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008680 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008681 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008682 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008683 assert(0 && "Shouldn't get here");
8684 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008685}
8686
Dan Gohman81b28ce2008-09-16 18:46:06 +00008687/// visitSelectInstWithICmp - Visit a SelectInst that has an
8688/// ICmpInst as its first operand.
8689///
8690Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8691 ICmpInst *ICI) {
8692 bool Changed = false;
8693 ICmpInst::Predicate Pred = ICI->getPredicate();
8694 Value *CmpLHS = ICI->getOperand(0);
8695 Value *CmpRHS = ICI->getOperand(1);
8696 Value *TrueVal = SI.getTrueValue();
8697 Value *FalseVal = SI.getFalseValue();
8698
8699 // Check cases where the comparison is with a constant that
8700 // can be adjusted to fit the min/max idiom. We may edit ICI in
8701 // place here, so make sure the select is the only user.
8702 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008703 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008704 switch (Pred) {
8705 default: break;
8706 case ICmpInst::ICMP_ULT:
8707 case ICmpInst::ICMP_SLT: {
8708 // X < MIN ? T : F --> F
8709 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8710 return ReplaceInstUsesWith(SI, FalseVal);
8711 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8712 Constant *AdjustedRHS = SubOne(CI);
8713 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8714 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8715 Pred = ICmpInst::getSwappedPredicate(Pred);
8716 CmpRHS = AdjustedRHS;
8717 std::swap(FalseVal, TrueVal);
8718 ICI->setPredicate(Pred);
8719 ICI->setOperand(1, CmpRHS);
8720 SI.setOperand(1, TrueVal);
8721 SI.setOperand(2, FalseVal);
8722 Changed = true;
8723 }
8724 break;
8725 }
8726 case ICmpInst::ICMP_UGT:
8727 case ICmpInst::ICMP_SGT: {
8728 // X > MAX ? T : F --> F
8729 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8730 return ReplaceInstUsesWith(SI, FalseVal);
8731 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8732 Constant *AdjustedRHS = AddOne(CI);
8733 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8734 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8735 Pred = ICmpInst::getSwappedPredicate(Pred);
8736 CmpRHS = AdjustedRHS;
8737 std::swap(FalseVal, TrueVal);
8738 ICI->setPredicate(Pred);
8739 ICI->setOperand(1, CmpRHS);
8740 SI.setOperand(1, TrueVal);
8741 SI.setOperand(2, FalseVal);
8742 Changed = true;
8743 }
8744 break;
8745 }
8746 }
8747
Dan Gohman1975d032008-10-30 20:40:10 +00008748 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8749 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008750 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008751 if (match(TrueVal, m_ConstantInt<-1>()) &&
8752 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008753 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008754 else if (match(TrueVal, m_ConstantInt<0>()) &&
8755 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008756 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8757
Dan Gohman1975d032008-10-30 20:40:10 +00008758 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8759 // If we are just checking for a icmp eq of a single bit and zext'ing it
8760 // to an integer, then shift the bit to the appropriate place and then
8761 // cast to integer to avoid the comparison.
8762 const APInt &Op1CV = CI->getValue();
8763
8764 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8765 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8766 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008767 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008768 Value *In = ICI->getOperand(0);
8769 Value *Sh = ConstantInt::get(In->getType(),
8770 In->getType()->getPrimitiveSizeInBits()-1);
8771 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8772 In->getName()+".lobit"),
8773 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008774 if (In->getType() != SI.getType())
8775 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008776 true/*SExt*/, "tmp", ICI);
8777
8778 if (Pred == ICmpInst::ICMP_SGT)
8779 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8780 In->getName()+".not"), *ICI);
8781
8782 return ReplaceInstUsesWith(SI, In);
8783 }
8784 }
8785 }
8786
Dan Gohman81b28ce2008-09-16 18:46:06 +00008787 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8788 // Transform (X == Y) ? X : Y -> Y
8789 if (Pred == ICmpInst::ICMP_EQ)
8790 return ReplaceInstUsesWith(SI, FalseVal);
8791 // Transform (X != Y) ? X : Y -> X
8792 if (Pred == ICmpInst::ICMP_NE)
8793 return ReplaceInstUsesWith(SI, TrueVal);
8794 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8795
8796 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8797 // Transform (X == Y) ? Y : X -> X
8798 if (Pred == ICmpInst::ICMP_EQ)
8799 return ReplaceInstUsesWith(SI, FalseVal);
8800 // Transform (X != Y) ? Y : X -> Y
8801 if (Pred == ICmpInst::ICMP_NE)
8802 return ReplaceInstUsesWith(SI, TrueVal);
8803 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8804 }
8805
8806 /// NOTE: if we wanted to, this is where to detect integer ABS
8807
8808 return Changed ? &SI : 0;
8809}
8810
Chris Lattner3d69f462004-03-12 05:52:32 +00008811Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008812 Value *CondVal = SI.getCondition();
8813 Value *TrueVal = SI.getTrueValue();
8814 Value *FalseVal = SI.getFalseValue();
8815
8816 // select true, X, Y -> X
8817 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008818 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008819 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008820
8821 // select C, X, X -> X
8822 if (TrueVal == FalseVal)
8823 return ReplaceInstUsesWith(SI, TrueVal);
8824
Chris Lattnere87597f2004-10-16 18:11:37 +00008825 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8826 return ReplaceInstUsesWith(SI, FalseVal);
8827 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8828 return ReplaceInstUsesWith(SI, TrueVal);
8829 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8830 if (isa<Constant>(TrueVal))
8831 return ReplaceInstUsesWith(SI, TrueVal);
8832 else
8833 return ReplaceInstUsesWith(SI, FalseVal);
8834 }
8835
Reid Spencer4fe16d62007-01-11 18:21:29 +00008836 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008837 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008838 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008839 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008840 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008841 } else {
8842 // Change: A = select B, false, C --> A = and !B, C
8843 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008844 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008845 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008846 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008847 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008848 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008849 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008850 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008851 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008852 } else {
8853 // Change: A = select B, C, true --> A = or !B, C
8854 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008855 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008856 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008857 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008858 }
8859 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008860
8861 // select a, b, a -> a&b
8862 // select a, a, b -> a|b
8863 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008864 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008865 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008866 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008867 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008868
Chris Lattner2eefe512004-04-09 19:05:30 +00008869 // Selecting between two integer constants?
8870 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8871 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008872 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008873 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008874 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008875 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008876 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008877 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008878 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008879 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008880 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008881 }
Chris Lattner457dd822004-06-09 07:59:58 +00008882
Reid Spencere4d87aa2006-12-23 06:05:41 +00008883 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008884
Reid Spencere4d87aa2006-12-23 06:05:41 +00008885 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008886 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008887 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008888 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008889 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008890 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008891 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008892 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008893 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008894 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008895 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008896 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008897
8898 // Then cast to the appropriate width.
8899 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00008900 }
8901 }
8902
8903
8904 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008905 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008906 // non-constant value, eliminate this whole mess. This corresponds to
8907 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008908 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008909 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008910 cast<Constant>(IC->getOperand(1))->isNullValue())
8911 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8912 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008913 isa<ConstantInt>(ICA->getOperand(1)) &&
8914 (ICA->getOperand(1) == TrueValC ||
8915 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008916 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8917 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008918 // know whether we have a icmp_ne or icmp_eq and whether the
8919 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008920 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008921 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008922 Value *V = ICA;
8923 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008924 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008925 Instruction::Xor, V, ICA->getOperand(1)), SI);
8926 return ReplaceInstUsesWith(SI, V);
8927 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008928 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008929 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008930
8931 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008932 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8933 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008934 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008935 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8936 // This is not safe in general for floating point:
8937 // consider X== -0, Y== +0.
8938 // It becomes safe if either operand is a nonzero constant.
8939 ConstantFP *CFPt, *CFPf;
8940 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8941 !CFPt->getValueAPF().isZero()) ||
8942 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8943 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008944 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008945 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008946 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008947 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008948 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008949 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00008950
Reid Spencere4d87aa2006-12-23 06:05:41 +00008951 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008952 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008953 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8954 // This is not safe in general for floating point:
8955 // consider X== -0, Y== +0.
8956 // It becomes safe if either operand is a nonzero constant.
8957 ConstantFP *CFPt, *CFPf;
8958 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8959 !CFPt->getValueAPF().isZero()) ||
8960 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8961 !CFPf->getValueAPF().isZero()))
8962 return ReplaceInstUsesWith(SI, FalseVal);
8963 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008964 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008965 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8966 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008967 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00008968 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008969 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00008970 }
8971
8972 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00008973 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8974 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8975 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00008976
Chris Lattner87875da2005-01-13 22:52:24 +00008977 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8978 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8979 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008980 Instruction *AddOp = 0, *SubOp = 0;
8981
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008982 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8983 if (TI->getOpcode() == FI->getOpcode())
8984 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8985 return IV;
8986
8987 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8988 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008989 if (TI->getOpcode() == Instruction::Sub &&
8990 FI->getOpcode() == Instruction::Add) {
8991 AddOp = FI; SubOp = TI;
8992 } else if (FI->getOpcode() == Instruction::Sub &&
8993 TI->getOpcode() == Instruction::Add) {
8994 AddOp = TI; SubOp = FI;
8995 }
8996
8997 if (AddOp) {
8998 Value *OtherAddOp = 0;
8999 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9000 OtherAddOp = AddOp->getOperand(1);
9001 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9002 OtherAddOp = AddOp->getOperand(0);
9003 }
9004
9005 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009006 // So at this point we know we have (Y -> OtherAddOp):
9007 // select C, (add X, Y), (sub X, Z)
9008 Value *NegVal; // Compute -Z
9009 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9010 NegVal = ConstantExpr::getNeg(C);
9011 } else {
9012 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009013 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009014 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009015
9016 Value *NewTrueOp = OtherAddOp;
9017 Value *NewFalseOp = NegVal;
9018 if (AddOp != TI)
9019 std::swap(NewTrueOp, NewFalseOp);
9020 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009021 SelectInst::Create(CondVal, NewTrueOp,
9022 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009023
9024 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009025 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009026 }
9027 }
9028 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009029
Chris Lattnere576b912004-04-09 23:46:01 +00009030 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009031 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009032 // See the comment above GetSelectFoldableOperands for a description of the
9033 // transformation we are doing here.
9034 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9035 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9036 !isa<Constant>(FalseVal))
9037 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9038 unsigned OpToFold = 0;
9039 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9040 OpToFold = 1;
9041 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9042 OpToFold = 2;
9043 }
9044
9045 if (OpToFold) {
9046 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009047 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009048 SelectInst::Create(SI.getCondition(),
9049 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009050 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009051 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009053 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009054 else {
9055 assert(0 && "Unknown instruction!!");
9056 }
9057 }
9058 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009059
Chris Lattnere576b912004-04-09 23:46:01 +00009060 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9061 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9062 !isa<Constant>(TrueVal))
9063 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9064 unsigned OpToFold = 0;
9065 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9066 OpToFold = 1;
9067 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9068 OpToFold = 2;
9069 }
9070
9071 if (OpToFold) {
9072 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009073 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009074 SelectInst::Create(SI.getCondition(), C,
9075 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009076 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009077 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009079 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009080 else
Chris Lattnere576b912004-04-09 23:46:01 +00009081 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009082 }
9083 }
9084 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009085
9086 if (BinaryOperator::isNot(CondVal)) {
9087 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9088 SI.setOperand(1, FalseVal);
9089 SI.setOperand(2, TrueVal);
9090 return &SI;
9091 }
9092
Chris Lattner3d69f462004-03-12 05:52:32 +00009093 return 0;
9094}
9095
Dan Gohmaneee962e2008-04-10 18:43:06 +00009096/// EnforceKnownAlignment - If the specified pointer points to an object that
9097/// we control, modify the object's alignment to PrefAlign. This isn't
9098/// often possible though. If alignment is important, a more reliable approach
9099/// is to simply align all global variables and allocation instructions to
9100/// their preferred alignment from the beginning.
9101///
9102static unsigned EnforceKnownAlignment(Value *V,
9103 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009104
Dan Gohmaneee962e2008-04-10 18:43:06 +00009105 User *U = dyn_cast<User>(V);
9106 if (!U) return Align;
9107
9108 switch (getOpcode(U)) {
9109 default: break;
9110 case Instruction::BitCast:
9111 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9112 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009113 // If all indexes are zero, it is just the alignment of the base pointer.
9114 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009115 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009116 if (!isa<Constant>(*i) ||
9117 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009118 AllZeroOperands = false;
9119 break;
9120 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009121
9122 if (AllZeroOperands) {
9123 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009124 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009125 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009126 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009127 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009128 }
9129
9130 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9131 // If there is a large requested alignment and we can, bump up the alignment
9132 // of the global.
9133 if (!GV->isDeclaration()) {
9134 GV->setAlignment(PrefAlign);
9135 Align = PrefAlign;
9136 }
9137 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9138 // If there is a requested alignment and if this is an alloca, round up. We
9139 // don't do this for malloc, because some systems can't respect the request.
9140 if (isa<AllocaInst>(AI)) {
9141 AI->setAlignment(PrefAlign);
9142 Align = PrefAlign;
9143 }
9144 }
9145
9146 return Align;
9147}
9148
9149/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9150/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9151/// and it is more than the alignment of the ultimate object, see if we can
9152/// increase the alignment of the ultimate object, making this check succeed.
9153unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9154 unsigned PrefAlign) {
9155 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9156 sizeof(PrefAlign) * CHAR_BIT;
9157 APInt Mask = APInt::getAllOnesValue(BitWidth);
9158 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9159 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9160 unsigned TrailZ = KnownZero.countTrailingOnes();
9161 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9162
9163 if (PrefAlign > Align)
9164 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9165
9166 // We don't need to make any adjustment.
9167 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009168}
9169
Chris Lattnerf497b022008-01-13 23:50:23 +00009170Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009171 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9172 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009173 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9174 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9175
9176 if (CopyAlign < MinAlign) {
9177 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9178 return MI;
9179 }
9180
9181 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9182 // load/store.
9183 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9184 if (MemOpLength == 0) return 0;
9185
Chris Lattner37ac6082008-01-14 00:28:35 +00009186 // Source and destination pointer types are always "i8*" for intrinsic. See
9187 // if the size is something we can handle with a single primitive load/store.
9188 // A single load+store correctly handles overlapping memory in the memmove
9189 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009190 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009191 if (Size == 0) return MI; // Delete this mem transfer.
9192
9193 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009194 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009195
Chris Lattner37ac6082008-01-14 00:28:35 +00009196 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009197 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009198
9199 // Memcpy forces the use of i8* for the source and destination. That means
9200 // that if you're using memcpy to move one double around, you'll get a cast
9201 // from double* to i8*. We'd much rather use a double load+store rather than
9202 // an i64 load+store, here because this improves the odds that the source or
9203 // dest address will be promotable. See if we can find a better type than the
9204 // integer datatype.
9205 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9206 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9207 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9208 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9209 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009210 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009211 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9212 if (STy->getNumElements() == 1)
9213 SrcETy = STy->getElementType(0);
9214 else
9215 break;
9216 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9217 if (ATy->getNumElements() == 1)
9218 SrcETy = ATy->getElementType();
9219 else
9220 break;
9221 } else
9222 break;
9223 }
9224
Dan Gohman8f8e2692008-05-23 01:52:21 +00009225 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009226 NewPtrTy = PointerType::getUnqual(SrcETy);
9227 }
9228 }
9229
9230
Chris Lattnerf497b022008-01-13 23:50:23 +00009231 // If the memcpy/memmove provides better alignment info than we can
9232 // infer, use it.
9233 SrcAlign = std::max(SrcAlign, CopyAlign);
9234 DstAlign = std::max(DstAlign, CopyAlign);
9235
9236 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9237 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009238 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9239 InsertNewInstBefore(L, *MI);
9240 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9241
9242 // Set the size of the copy to 0, it will be deleted on the next iteration.
9243 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9244 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009245}
Chris Lattner3d69f462004-03-12 05:52:32 +00009246
Chris Lattner69ea9d22008-04-30 06:39:11 +00009247Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9248 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9249 if (MI->getAlignment()->getZExtValue() < Alignment) {
9250 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9251 return MI;
9252 }
9253
9254 // Extract the length and alignment and fill if they are constant.
9255 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9256 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9257 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9258 return 0;
9259 uint64_t Len = LenC->getZExtValue();
9260 Alignment = MI->getAlignment()->getZExtValue();
9261
9262 // If the length is zero, this is a no-op
9263 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9264
9265 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9266 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9267 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9268
9269 Value *Dest = MI->getDest();
9270 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9271
9272 // Alignment 0 is identity for alignment 1 for memset, but not store.
9273 if (Alignment == 0) Alignment = 1;
9274
9275 // Extract the fill value and store.
9276 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9277 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9278 Alignment), *MI);
9279
9280 // Set the size of the copy to 0, it will be deleted on the next iteration.
9281 MI->setLength(Constant::getNullValue(LenC->getType()));
9282 return MI;
9283 }
9284
9285 return 0;
9286}
9287
9288
Chris Lattner8b0ea312006-01-13 20:11:04 +00009289/// visitCallInst - CallInst simplification. This mostly only handles folding
9290/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9291/// the heavy lifting.
9292///
Chris Lattner9fe38862003-06-19 17:00:31 +00009293Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009294 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9295 if (!II) return visitCallSite(&CI);
9296
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009297 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9298 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009299 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009300 bool Changed = false;
9301
9302 // memmove/cpy/set of zero bytes is a noop.
9303 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9304 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9305
Chris Lattner35b9e482004-10-12 04:52:52 +00009306 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009307 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009308 // Replace the instruction with just byte operations. We would
9309 // transform other cases to loads/stores, but we don't know if
9310 // alignment is sufficient.
9311 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009312 }
9313
Chris Lattner35b9e482004-10-12 04:52:52 +00009314 // If we have a memmove and the source operation is a constant global,
9315 // then the source and dest pointers can't alias, so we can change this
9316 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009317 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009318 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9319 if (GVSrc->isConstant()) {
9320 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009321 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9322 const Type *Tys[1];
9323 Tys[0] = CI.getOperand(3)->getType();
9324 CI.setOperand(0,
9325 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009326 Changed = true;
9327 }
Chris Lattnera935db82008-05-28 05:30:41 +00009328
9329 // memmove(x,x,size) -> noop.
9330 if (MMI->getSource() == MMI->getDest())
9331 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009332 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009333
Chris Lattner95a959d2006-03-06 20:18:44 +00009334 // If we can determine a pointer alignment that is bigger than currently
9335 // set, update the alignment.
9336 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009337 if (Instruction *I = SimplifyMemTransfer(MI))
9338 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009339 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9340 if (Instruction *I = SimplifyMemSet(MSI))
9341 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009342 }
9343
Chris Lattner8b0ea312006-01-13 20:11:04 +00009344 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009345 }
9346
9347 switch (II->getIntrinsicID()) {
9348 default: break;
9349 case Intrinsic::bswap:
9350 // bswap(bswap(x)) -> x
9351 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9352 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9353 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9354 break;
9355 case Intrinsic::ppc_altivec_lvx:
9356 case Intrinsic::ppc_altivec_lvxl:
9357 case Intrinsic::x86_sse_loadu_ps:
9358 case Intrinsic::x86_sse2_loadu_pd:
9359 case Intrinsic::x86_sse2_loadu_dq:
9360 // Turn PPC lvx -> load if the pointer is known aligned.
9361 // Turn X86 loadups -> load if the pointer is known aligned.
9362 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9363 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9364 PointerType::getUnqual(II->getType()),
9365 CI);
9366 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009367 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009368 break;
9369 case Intrinsic::ppc_altivec_stvx:
9370 case Intrinsic::ppc_altivec_stvxl:
9371 // Turn stvx -> store if the pointer is known aligned.
9372 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9373 const Type *OpPtrTy =
9374 PointerType::getUnqual(II->getOperand(1)->getType());
9375 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9376 return new StoreInst(II->getOperand(1), Ptr);
9377 }
9378 break;
9379 case Intrinsic::x86_sse_storeu_ps:
9380 case Intrinsic::x86_sse2_storeu_pd:
9381 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009382 // Turn X86 storeu -> store if the pointer is known aligned.
9383 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9384 const Type *OpPtrTy =
9385 PointerType::getUnqual(II->getOperand(2)->getType());
9386 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9387 return new StoreInst(II->getOperand(2), Ptr);
9388 }
9389 break;
9390
9391 case Intrinsic::x86_sse_cvttss2si: {
9392 // These intrinsics only demands the 0th element of its input vector. If
9393 // we can simplify the input based on that, do so now.
9394 uint64_t UndefElts;
9395 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9396 UndefElts)) {
9397 II->setOperand(1, V);
9398 return II;
9399 }
9400 break;
9401 }
9402
9403 case Intrinsic::ppc_altivec_vperm:
9404 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9405 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9406 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009407
Chris Lattner0521e3c2008-06-18 04:33:20 +00009408 // Check that all of the elements are integer constants or undefs.
9409 bool AllEltsOk = true;
9410 for (unsigned i = 0; i != 16; ++i) {
9411 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9412 !isa<UndefValue>(Mask->getOperand(i))) {
9413 AllEltsOk = false;
9414 break;
9415 }
9416 }
9417
9418 if (AllEltsOk) {
9419 // Cast the input vectors to byte vectors.
9420 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9421 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9422 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009423
Chris Lattner0521e3c2008-06-18 04:33:20 +00009424 // Only extract each element once.
9425 Value *ExtractedElts[32];
9426 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9427
Chris Lattnere2ed0572006-04-06 19:19:17 +00009428 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009429 if (isa<UndefValue>(Mask->getOperand(i)))
9430 continue;
9431 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9432 Idx &= 31; // Match the hardware behavior.
9433
9434 if (ExtractedElts[Idx] == 0) {
9435 Instruction *Elt =
9436 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9437 InsertNewInstBefore(Elt, CI);
9438 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009439 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009440
Chris Lattner0521e3c2008-06-18 04:33:20 +00009441 // Insert this value into the result vector.
9442 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9443 i, "tmp");
9444 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009445 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009446 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009447 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009448 }
9449 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009450
Chris Lattner0521e3c2008-06-18 04:33:20 +00009451 case Intrinsic::stackrestore: {
9452 // If the save is right next to the restore, remove the restore. This can
9453 // happen when variable allocas are DCE'd.
9454 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9455 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9456 BasicBlock::iterator BI = SS;
9457 if (&*++BI == II)
9458 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009459 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009460 }
9461
9462 // Scan down this block to see if there is another stack restore in the
9463 // same block without an intervening call/alloca.
9464 BasicBlock::iterator BI = II;
9465 TerminatorInst *TI = II->getParent()->getTerminator();
9466 bool CannotRemove = false;
9467 for (++BI; &*BI != TI; ++BI) {
9468 if (isa<AllocaInst>(BI)) {
9469 CannotRemove = true;
9470 break;
9471 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009472 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9473 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9474 // If there is a stackrestore below this one, remove this one.
9475 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9476 return EraseInstFromFunction(CI);
9477 // Otherwise, ignore the intrinsic.
9478 } else {
9479 // If we found a non-intrinsic call, we can't remove the stack
9480 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009481 CannotRemove = true;
9482 break;
9483 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009484 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009485 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009486
9487 // If the stack restore is in a return/unwind block and if there are no
9488 // allocas or calls between the restore and the return, nuke the restore.
9489 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9490 return EraseInstFromFunction(CI);
9491 break;
9492 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009493 }
9494
Chris Lattner8b0ea312006-01-13 20:11:04 +00009495 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009496}
9497
9498// InvokeInst simplification
9499//
9500Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009501 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009502}
9503
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009504/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9505/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009506static bool isSafeToEliminateVarargsCast(const CallSite CS,
9507 const CastInst * const CI,
9508 const TargetData * const TD,
9509 const int ix) {
9510 if (!CI->isLosslessCast())
9511 return false;
9512
9513 // The size of ByVal arguments is derived from the type, so we
9514 // can't change to a type with a different size. If the size were
9515 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009516 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009517 return true;
9518
9519 const Type* SrcTy =
9520 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9521 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9522 if (!SrcTy->isSized() || !DstTy->isSized())
9523 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009524 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009525 return false;
9526 return true;
9527}
9528
Chris Lattnera44d8a22003-10-07 22:32:43 +00009529// visitCallSite - Improvements for call and invoke instructions.
9530//
9531Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009532 bool Changed = false;
9533
9534 // If the callee is a constexpr cast of a function, attempt to move the cast
9535 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009536 if (transformConstExprCastCall(CS)) return 0;
9537
Chris Lattner6c266db2003-10-07 22:54:13 +00009538 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009539
Chris Lattner08b22ec2005-05-13 07:09:09 +00009540 if (Function *CalleeF = dyn_cast<Function>(Callee))
9541 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9542 Instruction *OldCall = CS.getInstruction();
9543 // If the call and callee calling conventions don't match, this call must
9544 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009545 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009546 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9547 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009548 if (!OldCall->use_empty())
9549 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9550 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9551 return EraseInstFromFunction(*OldCall);
9552 return 0;
9553 }
9554
Chris Lattner17be6352004-10-18 02:59:09 +00009555 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9556 // This instruction is not reachable, just remove it. We insert a store to
9557 // undef so that we know that this code is not reachable, despite the fact
9558 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009559 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009560 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009561 CS.getInstruction());
9562
9563 if (!CS.getInstruction()->use_empty())
9564 CS.getInstruction()->
9565 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9566
9567 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9568 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009569 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9570 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009571 }
Chris Lattner17be6352004-10-18 02:59:09 +00009572 return EraseInstFromFunction(*CS.getInstruction());
9573 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009574
Duncan Sandscdb6d922007-09-17 10:26:40 +00009575 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9576 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9577 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9578 return transformCallThroughTrampoline(CS);
9579
Chris Lattner6c266db2003-10-07 22:54:13 +00009580 const PointerType *PTy = cast<PointerType>(Callee->getType());
9581 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9582 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009583 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009584 // See if we can optimize any arguments passed through the varargs area of
9585 // the call.
9586 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009587 E = CS.arg_end(); I != E; ++I, ++ix) {
9588 CastInst *CI = dyn_cast<CastInst>(*I);
9589 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9590 *I = CI->getOperand(0);
9591 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009592 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009593 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009594 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009595
Duncan Sandsf0c33542007-12-19 21:13:37 +00009596 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009597 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009598 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009599 Changed = true;
9600 }
9601
Chris Lattner6c266db2003-10-07 22:54:13 +00009602 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009603}
9604
Chris Lattner9fe38862003-06-19 17:00:31 +00009605// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9606// attempt to move the cast to the arguments of the call/invoke.
9607//
9608bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9609 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9610 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009611 if (CE->getOpcode() != Instruction::BitCast ||
9612 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009613 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009614 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009615 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009616 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009617
9618 // Okay, this is a cast from a function to a different type. Unless doing so
9619 // would cause a type conversion of one of our arguments, change this call to
9620 // be a direct call with arguments casted to the appropriate types.
9621 //
9622 const FunctionType *FT = Callee->getFunctionType();
9623 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009624 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009625
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009626 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009627 return false; // TODO: Handle multiple return values.
9628
Chris Lattnerf78616b2004-01-14 06:06:08 +00009629 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009630 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009631 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009632 // Conversion is ok if changing from one pointer type to another or from
9633 // a pointer to an integer of the same size.
9634 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009635 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009636 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009637
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009638 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009639 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009640 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009641 return false; // Cannot transform this return value.
9642
Chris Lattner58d74912008-03-12 17:45:29 +00009643 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009644 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009645 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009646 return false; // Attribute not compatible with transformed value.
9647 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009648
Chris Lattnerf78616b2004-01-14 06:06:08 +00009649 // If the callsite is an invoke instruction, and the return value is used by
9650 // a PHI node in a successor, we cannot change the return type of the call
9651 // because there is no place to put the cast instruction (without breaking
9652 // the critical edge). Bail out in this case.
9653 if (!Caller->use_empty())
9654 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9655 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9656 UI != E; ++UI)
9657 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9658 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009659 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009660 return false;
9661 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009662
9663 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9664 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009665
Chris Lattner9fe38862003-06-19 17:00:31 +00009666 CallSite::arg_iterator AI = CS.arg_begin();
9667 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9668 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009669 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009670
9671 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009672 return false; // Cannot transform this parameter value.
9673
Devang Patel19c87462008-09-26 22:53:05 +00009674 if (CallerPAL.getParamAttributes(i + 1)
9675 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009676 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009677
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009678 // Converting from one pointer type to another or between a pointer and an
9679 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009680 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009681 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9682 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009683 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009684 }
9685
9686 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009687 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009688 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009689
Chris Lattner58d74912008-03-12 17:45:29 +00009690 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9691 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009692 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009693 // won't be dropping them. Check that these extra arguments have attributes
9694 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009695 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9696 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009697 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009698 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009699 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009700 return false;
9701 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009702
Chris Lattner9fe38862003-06-19 17:00:31 +00009703 // Okay, we decided that this is a safe thing to do: go ahead and start
9704 // inserting cast instructions as necessary...
9705 std::vector<Value*> Args;
9706 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009707 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009708 attrVec.reserve(NumCommonArgs);
9709
9710 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009711 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009712
9713 // If the return value is not being used, the type may not be compatible
9714 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009715 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009716
9717 // Add the new return attributes.
9718 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009719 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009720
9721 AI = CS.arg_begin();
9722 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9723 const Type *ParamTy = FT->getParamType(i);
9724 if ((*AI)->getType() == ParamTy) {
9725 Args.push_back(*AI);
9726 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009727 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009728 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009729 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009730 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009731 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009732
9733 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009734 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009735 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009736 }
9737
9738 // If the function takes more arguments than the call was taking, add them
9739 // now...
9740 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9741 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9742
9743 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009744 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009745 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009746 cerr << "WARNING: While resolving call to function '"
9747 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009748 } else {
9749 // Add all of the arguments in their promoted form to the arg list...
9750 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9751 const Type *PTy = getPromotedType((*AI)->getType());
9752 if (PTy != (*AI)->getType()) {
9753 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009754 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9755 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009756 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009757 InsertNewInstBefore(Cast, *Caller);
9758 Args.push_back(Cast);
9759 } else {
9760 Args.push_back(*AI);
9761 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009762
Duncan Sandse1e520f2008-01-13 08:02:44 +00009763 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009764 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009765 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009766 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009767 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009768 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009769
Devang Patel19c87462008-09-26 22:53:05 +00009770 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9771 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9772
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009773 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009774 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009775
Devang Patel05988662008-09-25 21:00:45 +00009776 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009777
Chris Lattner9fe38862003-06-19 17:00:31 +00009778 Instruction *NC;
9779 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009780 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009781 Args.begin(), Args.end(),
9782 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009783 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009784 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009785 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009786 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9787 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009788 CallInst *CI = cast<CallInst>(Caller);
9789 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009790 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009791 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009792 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009793 }
9794
Chris Lattner6934a042007-02-11 01:23:03 +00009795 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009796 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009797 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009798 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009799 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009800 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009801 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009802
9803 // If this is an invoke instruction, we should insert it after the first
9804 // non-phi, instruction in the normal successor block.
9805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009806 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009807 InsertNewInstBefore(NC, *I);
9808 } else {
9809 // Otherwise, it's a call, just insert cast right after the call instr
9810 InsertNewInstBefore(NC, *Caller);
9811 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009812 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009813 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009814 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009815 }
9816 }
9817
9818 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9819 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009820 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009821 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009822 return true;
9823}
9824
Duncan Sandscdb6d922007-09-17 10:26:40 +00009825// transformCallThroughTrampoline - Turn a call to a function created by the
9826// init_trampoline intrinsic into a direct call to the underlying function.
9827//
9828Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9829 Value *Callee = CS.getCalledValue();
9830 const PointerType *PTy = cast<PointerType>(Callee->getType());
9831 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009832 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009833
9834 // If the call already has the 'nest' attribute somewhere then give up -
9835 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009836 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009837 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009838
9839 IntrinsicInst *Tramp =
9840 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9841
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009842 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009843 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9844 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9845
Devang Patel05988662008-09-25 21:00:45 +00009846 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009847 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009848 unsigned NestIdx = 1;
9849 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009850 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009851
9852 // Look for a parameter marked with the 'nest' attribute.
9853 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9854 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009855 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009856 // Record the parameter type and any other attributes.
9857 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009858 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009859 break;
9860 }
9861
9862 if (NestTy) {
9863 Instruction *Caller = CS.getInstruction();
9864 std::vector<Value*> NewArgs;
9865 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9866
Devang Patel05988662008-09-25 21:00:45 +00009867 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009868 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009869
Duncan Sandscdb6d922007-09-17 10:26:40 +00009870 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009871 // mean appending it. Likewise for attributes.
9872
Devang Patel19c87462008-09-26 22:53:05 +00009873 // Add any result attributes.
9874 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009875 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009876
Duncan Sandscdb6d922007-09-17 10:26:40 +00009877 {
9878 unsigned Idx = 1;
9879 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9880 do {
9881 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009882 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009883 Value *NestVal = Tramp->getOperand(3);
9884 if (NestVal->getType() != NestTy)
9885 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9886 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009887 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009888 }
9889
9890 if (I == E)
9891 break;
9892
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009893 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009894 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009895 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009896 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009897 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009898
9899 ++Idx, ++I;
9900 } while (1);
9901 }
9902
Devang Patel19c87462008-09-26 22:53:05 +00009903 // Add any function attributes.
9904 if (Attributes Attr = Attrs.getFnAttributes())
9905 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9906
Duncan Sandscdb6d922007-09-17 10:26:40 +00009907 // The trampoline may have been bitcast to a bogus type (FTy).
9908 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009909 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009910
Duncan Sandscdb6d922007-09-17 10:26:40 +00009911 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009912 NewTypes.reserve(FTy->getNumParams()+1);
9913
Duncan Sandscdb6d922007-09-17 10:26:40 +00009914 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009915 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009916 {
9917 unsigned Idx = 1;
9918 FunctionType::param_iterator I = FTy->param_begin(),
9919 E = FTy->param_end();
9920
9921 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009922 if (Idx == NestIdx)
9923 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009924 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009925
9926 if (I == E)
9927 break;
9928
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009929 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009930 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009931
9932 ++Idx, ++I;
9933 } while (1);
9934 }
9935
9936 // Replace the trampoline call with a direct call. Let the generic
9937 // code sort out any function type mismatches.
9938 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009939 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009940 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9941 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +00009942 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009943
9944 Instruction *NewCaller;
9945 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009946 NewCaller = InvokeInst::Create(NewCallee,
9947 II->getNormalDest(), II->getUnwindDest(),
9948 NewArgs.begin(), NewArgs.end(),
9949 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009950 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009951 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009952 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009953 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9954 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009955 if (cast<CallInst>(Caller)->isTailCall())
9956 cast<CallInst>(NewCaller)->setTailCall();
9957 cast<CallInst>(NewCaller)->
9958 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009959 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009960 }
9961 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9962 Caller->replaceAllUsesWith(NewCaller);
9963 Caller->eraseFromParent();
9964 RemoveFromWorkList(Caller);
9965 return 0;
9966 }
9967 }
9968
9969 // Replace the trampoline call with a direct call. Since there is no 'nest'
9970 // parameter, there is no need to adjust the argument list. Let the generic
9971 // code sort out any function type mismatches.
9972 Constant *NewCallee =
9973 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9974 CS.setCalledFunction(NewCallee);
9975 return CS.getInstruction();
9976}
9977
Chris Lattner7da52b22006-11-01 04:51:18 +00009978/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9979/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9980/// and a single binop.
9981Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9982 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +00009983 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009984 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009985 Value *LHSVal = FirstInst->getOperand(0);
9986 Value *RHSVal = FirstInst->getOperand(1);
9987
9988 const Type *LHSType = LHSVal->getType();
9989 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009990
9991 // Scan to see if all operands are the same opcode, all have one use, and all
9992 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +00009993 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009994 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009995 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009996 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009997 // types or GEP's with different index types.
9998 I->getOperand(0)->getType() != LHSType ||
9999 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010000 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010001
10002 // If they are CmpInst instructions, check their predicates
10003 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10004 if (cast<CmpInst>(I)->getPredicate() !=
10005 cast<CmpInst>(FirstInst)->getPredicate())
10006 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010007
10008 // Keep track of which operand needs a phi node.
10009 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10010 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010011 }
10012
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010013 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010014
Chris Lattner7da52b22006-11-01 04:51:18 +000010015 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010016 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010017 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010018 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010019 NewLHS = PHINode::Create(LHSType,
10020 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010021 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10022 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010023 InsertNewInstBefore(NewLHS, PN);
10024 LHSVal = NewLHS;
10025 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010026
10027 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010028 NewRHS = PHINode::Create(RHSType,
10029 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010030 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10031 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010032 InsertNewInstBefore(NewRHS, PN);
10033 RHSVal = NewRHS;
10034 }
10035
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010036 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010037 if (NewLHS || NewRHS) {
10038 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10039 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10040 if (NewLHS) {
10041 Value *NewInLHS = InInst->getOperand(0);
10042 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10043 }
10044 if (NewRHS) {
10045 Value *NewInRHS = InInst->getOperand(1);
10046 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10047 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010048 }
10049 }
10050
Chris Lattner7da52b22006-11-01 04:51:18 +000010051 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010052 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010053 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10054 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10055 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010056}
10057
Chris Lattner05f18922008-12-01 02:34:36 +000010058Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10059 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10060
10061 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10062 FirstInst->op_end());
10063
10064 // Scan to see if all operands are the same opcode, all have one use, and all
10065 // kill their operands (i.e. the operands have one use).
10066 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10067 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10068 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10069 GEP->getNumOperands() != FirstInst->getNumOperands())
10070 return 0;
10071
10072 // Compare the operand lists.
10073 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10074 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10075 continue;
10076
10077 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10078 // if one of the PHIs has a constant for the index. The index may be
10079 // substantially cheaper to compute for the constants, so making it a
10080 // variable index could pessimize the path. This also handles the case
10081 // for struct indices, which must always be constant.
10082 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10083 isa<ConstantInt>(GEP->getOperand(op)))
10084 return 0;
10085
10086 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10087 return 0;
10088 FixedOperands[op] = 0; // Needs a PHI.
10089 }
10090 }
10091
10092 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10093 // that is variable.
10094 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10095
10096 bool HasAnyPHIs = false;
10097 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10098 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10099 Value *FirstOp = FirstInst->getOperand(i);
10100 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10101 FirstOp->getName()+".pn");
10102 InsertNewInstBefore(NewPN, PN);
10103
10104 NewPN->reserveOperandSpace(e);
10105 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10106 OperandPhis[i] = NewPN;
10107 FixedOperands[i] = NewPN;
10108 HasAnyPHIs = true;
10109 }
10110
10111
10112 // Add all operands to the new PHIs.
10113 if (HasAnyPHIs) {
10114 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10115 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10116 BasicBlock *InBB = PN.getIncomingBlock(i);
10117
10118 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10119 if (PHINode *OpPhi = OperandPhis[op])
10120 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10121 }
10122 }
10123
10124 Value *Base = FixedOperands[0];
10125 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10126 FixedOperands.end());
10127}
10128
10129
Chris Lattner76c73142006-11-01 07:13:54 +000010130/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10131/// of the block that defines it. This means that it must be obvious the value
10132/// of the load is not changed from the point of the load to the end of the
10133/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010134///
10135/// Finally, it is safe, but not profitable, to sink a load targetting a
10136/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10137/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +000010138static bool isSafeToSinkLoad(LoadInst *L) {
10139 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10140
10141 for (++BBI; BBI != E; ++BBI)
10142 if (BBI->mayWriteToMemory())
10143 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010144
10145 // Check for non-address taken alloca. If not address-taken already, it isn't
10146 // profitable to do this xform.
10147 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10148 bool isAddressTaken = false;
10149 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10150 UI != E; ++UI) {
10151 if (isa<LoadInst>(UI)) continue;
10152 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10153 // If storing TO the alloca, then the address isn't taken.
10154 if (SI->getOperand(1) == AI) continue;
10155 }
10156 isAddressTaken = true;
10157 break;
10158 }
10159
10160 if (!isAddressTaken)
10161 return false;
10162 }
10163
Chris Lattner76c73142006-11-01 07:13:54 +000010164 return true;
10165}
10166
Chris Lattner9fe38862003-06-19 17:00:31 +000010167
Chris Lattnerbac32862004-11-14 19:13:23 +000010168// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10169// operator and they all are only used by the PHI, PHI together their
10170// inputs, and do the operation once, to the result of the PHI.
10171Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10172 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10173
10174 // Scan the instruction, looking for input operations that can be folded away.
10175 // If all input operands to the phi are the same instruction (e.g. a cast from
10176 // the same type or "+42") we can pull the operation through the PHI, reducing
10177 // code size and simplifying code.
10178 Constant *ConstantOp = 0;
10179 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010180 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010181 if (isa<CastInst>(FirstInst)) {
10182 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010183 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010184 // Can fold binop, compare or shift here if the RHS is a constant,
10185 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010186 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010187 if (ConstantOp == 0)
10188 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010189 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10190 isVolatile = LI->isVolatile();
10191 // We can't sink the load if the loaded value could be modified between the
10192 // load and the PHI.
10193 if (LI->getParent() != PN.getIncomingBlock(0) ||
10194 !isSafeToSinkLoad(LI))
10195 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010196
10197 // If the PHI is of volatile loads and the load block has multiple
10198 // successors, sinking it would remove a load of the volatile value from
10199 // the path through the other successor.
10200 if (isVolatile &&
10201 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10202 return 0;
10203
Chris Lattner9c080502006-11-01 07:43:41 +000010204 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010205 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010206 } else {
10207 return 0; // Cannot fold this operation.
10208 }
10209
10210 // Check to see if all arguments are the same operation.
10211 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10212 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10213 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010214 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010215 return 0;
10216 if (CastSrcTy) {
10217 if (I->getOperand(0)->getType() != CastSrcTy)
10218 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010219 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010220 // We can't sink the load if the loaded value could be modified between
10221 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010222 if (LI->isVolatile() != isVolatile ||
10223 LI->getParent() != PN.getIncomingBlock(i) ||
10224 !isSafeToSinkLoad(LI))
10225 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010226
Chris Lattner71042962008-07-08 17:18:32 +000010227 // If the PHI is of volatile loads and the load block has multiple
10228 // successors, sinking it would remove a load of the volatile value from
10229 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010230 if (isVolatile &&
10231 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10232 return 0;
10233
10234
Chris Lattnerbac32862004-11-14 19:13:23 +000010235 } else if (I->getOperand(1) != ConstantOp) {
10236 return 0;
10237 }
10238 }
10239
10240 // Okay, they are all the same operation. Create a new PHI node of the
10241 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010242 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10243 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010244 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010245
10246 Value *InVal = FirstInst->getOperand(0);
10247 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010248
10249 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010250 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10251 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10252 if (NewInVal != InVal)
10253 InVal = 0;
10254 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10255 }
10256
10257 Value *PhiVal;
10258 if (InVal) {
10259 // The new PHI unions all of the same values together. This is really
10260 // common, so we handle it intelligently here for compile-time speed.
10261 PhiVal = InVal;
10262 delete NewPN;
10263 } else {
10264 InsertNewInstBefore(NewPN, PN);
10265 PhiVal = NewPN;
10266 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010267
Chris Lattnerbac32862004-11-14 19:13:23 +000010268 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010269 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010270 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010271 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010272 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010273 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010274 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010275 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010276 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10277
10278 // If this was a volatile load that we are merging, make sure to loop through
10279 // and mark all the input loads as non-volatile. If we don't do this, we will
10280 // insert a new volatile load and the old ones will not be deletable.
10281 if (isVolatile)
10282 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10283 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10284
10285 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010286}
Chris Lattnera1be5662002-05-02 17:06:02 +000010287
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010288/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10289/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010290static bool DeadPHICycle(PHINode *PN,
10291 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010292 if (PN->use_empty()) return true;
10293 if (!PN->hasOneUse()) return false;
10294
10295 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010296 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010297 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010298
10299 // Don't scan crazily complex things.
10300 if (PotentiallyDeadPHIs.size() == 16)
10301 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010302
10303 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10304 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010305
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010306 return false;
10307}
10308
Chris Lattnercf5008a2007-11-06 21:52:06 +000010309/// PHIsEqualValue - Return true if this phi node is always equal to
10310/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10311/// z = some value; x = phi (y, z); y = phi (x, z)
10312static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10313 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10314 // See if we already saw this PHI node.
10315 if (!ValueEqualPHIs.insert(PN))
10316 return true;
10317
10318 // Don't scan crazily complex things.
10319 if (ValueEqualPHIs.size() == 16)
10320 return false;
10321
10322 // Scan the operands to see if they are either phi nodes or are equal to
10323 // the value.
10324 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10325 Value *Op = PN->getIncomingValue(i);
10326 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10327 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10328 return false;
10329 } else if (Op != NonPhiInVal)
10330 return false;
10331 }
10332
10333 return true;
10334}
10335
10336
Chris Lattner473945d2002-05-06 18:06:38 +000010337// PHINode simplification
10338//
Chris Lattner7e708292002-06-25 16:13:24 +000010339Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010340 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010341 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010342
Owen Anderson7e057142006-07-10 22:03:18 +000010343 if (Value *V = PN.hasConstantValue())
10344 return ReplaceInstUsesWith(PN, V);
10345
Owen Anderson7e057142006-07-10 22:03:18 +000010346 // If all PHI operands are the same operation, pull them through the PHI,
10347 // reducing code size.
10348 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010349 isa<Instruction>(PN.getIncomingValue(1)) &&
10350 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10351 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10352 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10353 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010354 PN.getIncomingValue(0)->hasOneUse())
10355 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10356 return Result;
10357
10358 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10359 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10360 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010361 if (PN.hasOneUse()) {
10362 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10363 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010364 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010365 PotentiallyDeadPHIs.insert(&PN);
10366 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10367 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10368 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010369
10370 // If this phi has a single use, and if that use just computes a value for
10371 // the next iteration of a loop, delete the phi. This occurs with unused
10372 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10373 // common case here is good because the only other things that catch this
10374 // are induction variable analysis (sometimes) and ADCE, which is only run
10375 // late.
10376 if (PHIUser->hasOneUse() &&
10377 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10378 PHIUser->use_back() == &PN) {
10379 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10380 }
10381 }
Owen Anderson7e057142006-07-10 22:03:18 +000010382
Chris Lattnercf5008a2007-11-06 21:52:06 +000010383 // We sometimes end up with phi cycles that non-obviously end up being the
10384 // same value, for example:
10385 // z = some value; x = phi (y, z); y = phi (x, z)
10386 // where the phi nodes don't necessarily need to be in the same block. Do a
10387 // quick check to see if the PHI node only contains a single non-phi value, if
10388 // so, scan to see if the phi cycle is actually equal to that value.
10389 {
10390 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10391 // Scan for the first non-phi operand.
10392 while (InValNo != NumOperandVals &&
10393 isa<PHINode>(PN.getIncomingValue(InValNo)))
10394 ++InValNo;
10395
10396 if (InValNo != NumOperandVals) {
10397 Value *NonPhiInVal = PN.getOperand(InValNo);
10398
10399 // Scan the rest of the operands to see if there are any conflicts, if so
10400 // there is no need to recursively scan other phis.
10401 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10402 Value *OpVal = PN.getIncomingValue(InValNo);
10403 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10404 break;
10405 }
10406
10407 // If we scanned over all operands, then we have one unique value plus
10408 // phi values. Scan PHI nodes to see if they all merge in each other or
10409 // the value.
10410 if (InValNo == NumOperandVals) {
10411 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10412 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10413 return ReplaceInstUsesWith(PN, NonPhiInVal);
10414 }
10415 }
10416 }
Chris Lattner60921c92003-12-19 05:58:40 +000010417 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010418}
10419
Reid Spencer17212df2006-12-12 09:18:51 +000010420static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10421 Instruction *InsertPoint,
10422 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010423 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10424 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010425 // We must cast correctly to the pointer type. Ensure that we
10426 // sign extend the integer value if it is smaller as this is
10427 // used for address computation.
10428 Instruction::CastOps opcode =
10429 (VTySize < PtrSize ? Instruction::SExt :
10430 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10431 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010432}
10433
Chris Lattnera1be5662002-05-02 17:06:02 +000010434
Chris Lattner7e708292002-06-25 16:13:24 +000010435Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010436 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010437 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010438 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010439 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010440 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010441
Chris Lattnere87597f2004-10-16 18:11:37 +000010442 if (isa<UndefValue>(GEP.getOperand(0)))
10443 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10444
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010445 bool HasZeroPointerIndex = false;
10446 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10447 HasZeroPointerIndex = C->isNullValue();
10448
10449 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010450 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010451
Chris Lattner28977af2004-04-05 01:30:19 +000010452 // Eliminate unneeded casts for indices.
10453 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010454
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010455 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010456 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10457 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010458 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010459 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010460 if (CI->getOpcode() == Instruction::ZExt ||
10461 CI->getOpcode() == Instruction::SExt) {
10462 const Type *SrcTy = CI->getOperand(0)->getType();
10463 // We can eliminate a cast from i32 to i64 iff the target
10464 // is a 32-bit pointer target.
10465 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10466 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010467 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010468 }
10469 }
10470 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010471 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010472 // to what we need. If narrower, sign-extend it to what we need.
10473 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010474 // insert it. This explicit cast can make subsequent optimizations more
10475 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010476 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010477 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010478 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010479 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010480 MadeChange = true;
10481 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010482 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10483 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010484 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010485 MadeChange = true;
10486 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010487 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10488 if (Constant *C = dyn_cast<Constant>(Op)) {
10489 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10490 MadeChange = true;
10491 } else {
10492 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10493 GEP);
10494 *i = Op;
10495 MadeChange = true;
10496 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010497 }
Chris Lattner28977af2004-04-05 01:30:19 +000010498 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010499 }
Chris Lattner28977af2004-04-05 01:30:19 +000010500 if (MadeChange) return &GEP;
10501
Chris Lattner90ac28c2002-08-02 19:29:35 +000010502 // Combine Indices - If the source pointer to this getelementptr instruction
10503 // is a getelementptr instruction, combine the indices of the two
10504 // getelementptr instructions into a single instruction.
10505 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010506 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010507 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010508 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010509
10510 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010511 // Note that if our source is a gep chain itself that we wait for that
10512 // chain to be resolved before we perform this transformation. This
10513 // avoids us creating a TON of code in some cases.
10514 //
10515 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10516 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10517 return 0; // Wait until our source is folded to completion.
10518
Chris Lattner72588fc2007-02-15 22:48:32 +000010519 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010520
10521 // Find out whether the last index in the source GEP is a sequential idx.
10522 bool EndsWithSequential = false;
10523 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10524 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010525 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010526
Chris Lattner90ac28c2002-08-02 19:29:35 +000010527 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010528 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010529 // Replace: gep (gep %P, long B), long A, ...
10530 // With: T = long A+B; gep %P, T, ...
10531 //
Chris Lattner620ce142004-05-07 22:09:22 +000010532 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010533 if (SO1 == Constant::getNullValue(SO1->getType())) {
10534 Sum = GO1;
10535 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10536 Sum = SO1;
10537 } else {
10538 // If they aren't the same type, convert both to an integer of the
10539 // target's pointer size.
10540 if (SO1->getType() != GO1->getType()) {
10541 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010542 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010543 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010544 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010545 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010546 unsigned PS = TD->getPointerSizeInBits();
10547 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010548 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010549 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010550
Duncan Sands514ab342007-11-01 20:53:16 +000010551 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010552 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010553 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010554 } else {
10555 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010556 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10557 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010558 }
10559 }
10560 }
Chris Lattner620ce142004-05-07 22:09:22 +000010561 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10562 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10563 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010564 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010565 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010566 }
Chris Lattner28977af2004-04-05 01:30:19 +000010567 }
Chris Lattner620ce142004-05-07 22:09:22 +000010568
10569 // Recycle the GEP we already have if possible.
10570 if (SrcGEPOperands.size() == 2) {
10571 GEP.setOperand(0, SrcGEPOperands[0]);
10572 GEP.setOperand(1, Sum);
10573 return &GEP;
10574 } else {
10575 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10576 SrcGEPOperands.end()-1);
10577 Indices.push_back(Sum);
10578 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10579 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010580 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010581 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010582 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010583 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010584 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10585 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010586 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10587 }
10588
10589 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010590 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10591 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010592
Chris Lattner620ce142004-05-07 22:09:22 +000010593 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010594 // GEP of global variable. If all of the indices for this GEP are
10595 // constants, we can promote this to a constexpr instead of an instruction.
10596
10597 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010598 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010599 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10600 for (; I != E && isa<Constant>(*I); ++I)
10601 Indices.push_back(cast<Constant>(*I));
10602
10603 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010604 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10605 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010606
10607 // Replace all uses of the GEP with the new constexpr...
10608 return ReplaceInstUsesWith(GEP, CE);
10609 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010610 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010611 if (!isa<PointerType>(X->getType())) {
10612 // Not interesting. Source pointer must be a cast from pointer.
10613 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010614 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10615 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010616 //
10617 // This occurs when the program declares an array extern like "int X[];"
10618 //
10619 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10620 const PointerType *XTy = cast<PointerType>(X->getType());
10621 if (const ArrayType *XATy =
10622 dyn_cast<ArrayType>(XTy->getElementType()))
10623 if (const ArrayType *CATy =
10624 dyn_cast<ArrayType>(CPTy->getElementType()))
10625 if (CATy->getElementType() == XATy->getElementType()) {
10626 // At this point, we know that the cast source type is a pointer
10627 // to an array of the same type as the destination pointer
10628 // array. Because the array type is never stepped over (there
10629 // is a leading zero) we can fold the cast into this GEP.
10630 GEP.setOperand(0, X);
10631 return &GEP;
10632 }
10633 } else if (GEP.getNumOperands() == 2) {
10634 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010635 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10636 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010637 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10638 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10639 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010640 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10641 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010642 Value *Idx[2];
10643 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10644 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010645 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010646 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010647 // V and GEP are both pointer types --> BitCast
10648 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010649 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010650
10651 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010652 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010653 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010654 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010655
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010656 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010657 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010658 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010659
10660 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10661 // allow either a mul, shift, or constant here.
10662 Value *NewIdx = 0;
10663 ConstantInt *Scale = 0;
10664 if (ArrayEltSize == 1) {
10665 NewIdx = GEP.getOperand(1);
10666 Scale = ConstantInt::get(NewIdx->getType(), 1);
10667 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010668 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010669 Scale = CI;
10670 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10671 if (Inst->getOpcode() == Instruction::Shl &&
10672 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010673 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10674 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10675 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010676 NewIdx = Inst->getOperand(0);
10677 } else if (Inst->getOpcode() == Instruction::Mul &&
10678 isa<ConstantInt>(Inst->getOperand(1))) {
10679 Scale = cast<ConstantInt>(Inst->getOperand(1));
10680 NewIdx = Inst->getOperand(0);
10681 }
10682 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010683
Chris Lattner7835cdd2005-09-13 18:36:04 +000010684 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010685 // out, perform the transformation. Note, we don't know whether Scale is
10686 // signed or not. We'll use unsigned version of division/modulo
10687 // operation after making sure Scale doesn't have the sign bit set.
10688 if (Scale && Scale->getSExtValue() >= 0LL &&
10689 Scale->getZExtValue() % ArrayEltSize == 0) {
10690 Scale = ConstantInt::get(Scale->getType(),
10691 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010692 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010693 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010694 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010695 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010696 NewIdx = InsertNewInstBefore(Sc, GEP);
10697 }
10698
10699 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010700 Value *Idx[2];
10701 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10702 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010703 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010704 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010705 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10706 // The NewGEP must be pointer typed, so must the old one -> BitCast
10707 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010708 }
10709 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010710 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010711 }
Chris Lattner58407792009-01-09 04:53:57 +000010712
Chris Lattner46cd5a12009-01-09 05:44:56 +000010713 /// See if we can simplify:
10714 /// X = bitcast A to B*
10715 /// Y = gep X, <...constant indices...>
10716 /// into a gep of the original struct. This is important for SROA and alias
10717 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010718 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010719 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10720 // Determine how much the GEP moves the pointer. We are guaranteed to get
10721 // a constant back from EmitGEPOffset.
10722 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10723 int64_t Offset = OffsetV->getSExtValue();
10724
10725 // If this GEP instruction doesn't move the pointer, just replace the GEP
10726 // with a bitcast of the real input to the dest type.
10727 if (Offset == 0) {
10728 // If the bitcast is of an allocation, and the allocation will be
10729 // converted to match the type of the cast, don't touch this.
10730 if (isa<AllocationInst>(BCI->getOperand(0))) {
10731 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10732 if (Instruction *I = visitBitCast(*BCI)) {
10733 if (I != BCI) {
10734 I->takeName(BCI);
10735 BCI->getParent()->getInstList().insert(BCI, I);
10736 ReplaceInstUsesWith(*BCI, I);
10737 }
10738 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010739 }
Chris Lattner58407792009-01-09 04:53:57 +000010740 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010741 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010742 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010743
10744 // Otherwise, if the offset is non-zero, we need to find out if there is a
10745 // field at Offset in 'A's type. If so, we can pull the cast through the
10746 // GEP.
10747 SmallVector<Value*, 8> NewIndices;
10748 const Type *InTy =
10749 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10750 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10751 Instruction *NGEP =
10752 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10753 NewIndices.end());
10754 if (NGEP->getType() == GEP.getType()) return NGEP;
10755 InsertNewInstBefore(NGEP, GEP);
10756 NGEP->takeName(&GEP);
10757 return new BitCastInst(NGEP, GEP.getType());
10758 }
Chris Lattner58407792009-01-09 04:53:57 +000010759 }
10760 }
10761
Chris Lattner8a2a3112001-12-14 16:52:21 +000010762 return 0;
10763}
10764
Chris Lattner0864acf2002-11-04 16:18:53 +000010765Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10766 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010767 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010768 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10769 const Type *NewTy =
10770 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010771 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010772
10773 // Create and insert the replacement instruction...
10774 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010775 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010776 else {
10777 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010778 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010779 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010780
10781 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010782
Chris Lattner0864acf2002-11-04 16:18:53 +000010783 // Scan to the end of the allocation instructions, to skip over a block of
10784 // allocas if possible...
10785 //
10786 BasicBlock::iterator It = New;
10787 while (isa<AllocationInst>(*It)) ++It;
10788
10789 // Now that I is pointing to the first non-allocation-inst in the block,
10790 // insert our getelementptr instruction...
10791 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010792 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010793 Value *Idx[2];
10794 Idx[0] = NullIdx;
10795 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010796 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10797 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010798
10799 // Now make everything use the getelementptr instead of the original
10800 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010801 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010802 } else if (isa<UndefValue>(AI.getArraySize())) {
10803 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010804 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010805 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010806
Dan Gohman6893cd72009-01-13 20:18:38 +000010807 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10808 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10809 // Note that we only do this for alloca's, because malloc should allocate and
10810 // return a unique pointer, even for a zero byte allocation.
10811 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10812 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10813
10814 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10815 if (AI.getAlignment() == 0)
10816 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10817 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010818
Chris Lattner0864acf2002-11-04 16:18:53 +000010819 return 0;
10820}
10821
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010822Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10823 Value *Op = FI.getOperand(0);
10824
Chris Lattner17be6352004-10-18 02:59:09 +000010825 // free undef -> unreachable.
10826 if (isa<UndefValue>(Op)) {
10827 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010828 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010829 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010830 return EraseInstFromFunction(FI);
10831 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010832
Chris Lattner6160e852004-02-28 04:57:37 +000010833 // If we have 'free null' delete the instruction. This can happen in stl code
10834 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010835 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010836 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010837
10838 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10839 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10840 FI.setOperand(0, CI->getOperand(0));
10841 return &FI;
10842 }
10843
10844 // Change free (gep X, 0,0,0,0) into free(X)
10845 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10846 if (GEPI->hasAllZeroIndices()) {
10847 AddToWorkList(GEPI);
10848 FI.setOperand(0, GEPI->getOperand(0));
10849 return &FI;
10850 }
10851 }
10852
10853 // Change free(malloc) into nothing, if the malloc has a single use.
10854 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10855 if (MI->hasOneUse()) {
10856 EraseInstFromFunction(FI);
10857 return EraseInstFromFunction(*MI);
10858 }
Chris Lattner6160e852004-02-28 04:57:37 +000010859
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010860 return 0;
10861}
10862
10863
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010864/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010865static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010866 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010867 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010868 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010869
Devang Patel99db6ad2007-10-18 19:52:32 +000010870 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10871 // Instead of loading constant c string, use corresponding integer value
10872 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010873 std::string Str;
10874 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010875 unsigned len = Str.length();
10876 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10877 unsigned numBits = Ty->getPrimitiveSizeInBits();
10878 // Replace LI with immediate integer store.
10879 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010880 APInt StrVal(numBits, 0);
10881 APInt SingleChar(numBits, 0);
10882 if (TD->isLittleEndian()) {
10883 for (signed i = len-1; i >= 0; i--) {
10884 SingleChar = (uint64_t) Str[i];
10885 StrVal = (StrVal << 8) | SingleChar;
10886 }
10887 } else {
10888 for (unsigned i = 0; i < len; i++) {
10889 SingleChar = (uint64_t) Str[i];
10890 StrVal = (StrVal << 8) | SingleChar;
10891 }
10892 // Append NULL at the end.
10893 SingleChar = 0;
10894 StrVal = (StrVal << 8) | SingleChar;
10895 }
10896 Value *NL = ConstantInt::get(StrVal);
10897 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010898 }
10899 }
10900 }
10901
Chris Lattnerb89e0712004-07-13 01:49:43 +000010902 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010903 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010904 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010905
Reid Spencer42230162007-01-22 05:51:25 +000010906 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010907 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010908 // If the source is an array, the code below will not succeed. Check to
10909 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10910 // constants.
10911 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10912 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10913 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010914 Value *Idxs[2];
10915 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10916 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010917 SrcTy = cast<PointerType>(CastOp->getType());
10918 SrcPTy = SrcTy->getElementType();
10919 }
10920
Reid Spencer42230162007-01-22 05:51:25 +000010921 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010922 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010923 // Do not allow turning this into a load of an integer, which is then
10924 // casted to a pointer, this pessimizes pointer analysis a lot.
10925 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010926 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10927 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010928
Chris Lattnerf9527852005-01-31 04:50:46 +000010929 // Okay, we are casting from one integer or pointer type to another of
10930 // the same size. Instead of casting the pointer before the load, cast
10931 // the result of the loaded value.
10932 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10933 CI->getName(),
10934 LI.isVolatile()),LI);
10935 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010936 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010937 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010938 }
10939 }
10940 return 0;
10941}
10942
Chris Lattnerc10aced2004-09-19 18:43:46 +000010943/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010944/// from this value cannot trap. If it is not obviously safe to load from the
10945/// specified pointer, we do a quick local scan of the basic block containing
10946/// ScanFrom, to determine if the address is already accessed.
10947static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010948 // If it is an alloca it is always safe to load from.
10949 if (isa<AllocaInst>(V)) return true;
10950
Duncan Sands46318cd2007-09-19 10:25:38 +000010951 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010952 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010953 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010954 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010955
10956 // Otherwise, be a little bit agressive by scanning the local block where we
10957 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010958 // from/to. If so, the previous load or store would have already trapped,
10959 // so there is no harm doing an extra load (also, CSE will later eliminate
10960 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010961 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10962
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010963 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010964 --BBI;
10965
Chris Lattner2de3fec2008-06-20 05:12:56 +000010966 // If we see a free or a call (which might do a free) the pointer could be
10967 // marked invalid.
10968 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10969 return false;
10970
Chris Lattner8a375202004-09-19 19:18:10 +000010971 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10972 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010973 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010974 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010975 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010976
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010977 }
Chris Lattner8a375202004-09-19 19:18:10 +000010978 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010979}
10980
Chris Lattner833b8a42003-06-26 05:06:25 +000010981Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10982 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010983
Dan Gohman9941f742007-07-20 16:34:21 +000010984 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010985 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10986 if (KnownAlign >
10987 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10988 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010989 LI.setAlignment(KnownAlign);
10990
Chris Lattner37366c12005-05-01 04:24:53 +000010991 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010992 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010993 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010994 return Res;
10995
10996 // None of the following transforms are legal for volatile loads.
10997 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010998
Dan Gohman2276a7b2008-10-15 23:19:35 +000010999 // Do really simple store-to-load forwarding and load CSE, to catch cases
11000 // where there are several consequtive memory accesses to the same location,
11001 // separated by a few arithmetic operations.
11002 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011003 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11004 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011005
Christopher Lambb15147e2007-12-29 07:56:53 +000011006 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11007 const Value *GEPI0 = GEPI->getOperand(0);
11008 // TODO: Consider a target hook for valid address spaces for this xform.
11009 if (isa<ConstantPointerNull>(GEPI0) &&
11010 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011011 // Insert a new store to null instruction before the load to indicate
11012 // that this code is not reachable. We do this instead of inserting
11013 // an unreachable instruction directly because we cannot modify the
11014 // CFG.
11015 new StoreInst(UndefValue::get(LI.getType()),
11016 Constant::getNullValue(Op->getType()), &LI);
11017 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11018 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011019 }
Chris Lattner37366c12005-05-01 04:24:53 +000011020
Chris Lattnere87597f2004-10-16 18:11:37 +000011021 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011022 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011023 // TODO: Consider a target hook for valid address spaces for this xform.
11024 if (isa<UndefValue>(C) || (C->isNullValue() &&
11025 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011026 // Insert a new store to null instruction before the load to indicate that
11027 // this code is not reachable. We do this instead of inserting an
11028 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011029 new StoreInst(UndefValue::get(LI.getType()),
11030 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011031 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011032 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011033
Chris Lattnere87597f2004-10-16 18:11:37 +000011034 // Instcombine load (constant global) into the value loaded.
11035 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011036 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011037 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011038
Chris Lattnere87597f2004-10-16 18:11:37 +000011039 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011040 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011041 if (CE->getOpcode() == Instruction::GetElementPtr) {
11042 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011043 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011044 if (Constant *V =
11045 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011046 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011047 if (CE->getOperand(0)->isNullValue()) {
11048 // Insert a new store to null instruction before the load to indicate
11049 // that this code is not reachable. We do this instead of inserting
11050 // an unreachable instruction directly because we cannot modify the
11051 // CFG.
11052 new StoreInst(UndefValue::get(LI.getType()),
11053 Constant::getNullValue(Op->getType()), &LI);
11054 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11055 }
11056
Reid Spencer3da59db2006-11-27 01:05:10 +000011057 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011058 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011059 return Res;
11060 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011061 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011062 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011063
11064 // If this load comes from anywhere in a constant global, and if the global
11065 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011066 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011067 if (GV->isConstant() && GV->hasInitializer()) {
11068 if (GV->getInitializer()->isNullValue())
11069 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11070 else if (isa<UndefValue>(GV->getInitializer()))
11071 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11072 }
11073 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011074
Chris Lattner37366c12005-05-01 04:24:53 +000011075 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011076 // Change select and PHI nodes to select values instead of addresses: this
11077 // helps alias analysis out a lot, allows many others simplifications, and
11078 // exposes redundancy in the code.
11079 //
11080 // Note that we cannot do the transformation unless we know that the
11081 // introduced loads cannot trap! Something like this is valid as long as
11082 // the condition is always false: load (select bool %C, int* null, int* %G),
11083 // but it would not be valid if we transformed it to load from null
11084 // unconditionally.
11085 //
11086 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11087 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011088 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11089 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011090 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011091 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011092 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011093 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011094 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011095 }
11096
Chris Lattner684fe212004-09-23 15:46:00 +000011097 // load (select (cond, null, P)) -> load P
11098 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11099 if (C->isNullValue()) {
11100 LI.setOperand(0, SI->getOperand(2));
11101 return &LI;
11102 }
11103
11104 // load (select (cond, P, null)) -> load P
11105 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11106 if (C->isNullValue()) {
11107 LI.setOperand(0, SI->getOperand(1));
11108 return &LI;
11109 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011110 }
11111 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011112 return 0;
11113}
11114
Reid Spencer55af2b52007-01-19 21:20:31 +000011115/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011116/// when possible. This makes it generally easy to do alias analysis and/or
11117/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011118static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11119 User *CI = cast<User>(SI.getOperand(1));
11120 Value *CastOp = CI->getOperand(0);
11121
11122 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011123 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11124 if (SrcTy == 0) return 0;
11125
11126 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011127
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011128 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11129 return 0;
11130
Chris Lattner3914f722009-01-24 01:00:13 +000011131 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11132 /// to its first element. This allows us to handle things like:
11133 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11134 /// on 32-bit hosts.
11135 SmallVector<Value*, 4> NewGEPIndices;
11136
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011137 // If the source is an array, the code below will not succeed. Check to
11138 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11139 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011140 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11141 // Index through pointer.
11142 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11143 NewGEPIndices.push_back(Zero);
11144
11145 while (1) {
11146 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011147 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011148 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011149 NewGEPIndices.push_back(Zero);
11150 SrcPTy = STy->getElementType(0);
11151 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11152 NewGEPIndices.push_back(Zero);
11153 SrcPTy = ATy->getElementType();
11154 } else {
11155 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011156 }
Chris Lattner3914f722009-01-24 01:00:13 +000011157 }
11158
11159 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11160 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011161
11162 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11163 return 0;
11164
Chris Lattner71759c42009-01-16 20:12:52 +000011165 // If the pointers point into different address spaces or if they point to
11166 // values with different sizes, we can't do the transformation.
11167 if (SrcTy->getAddressSpace() !=
11168 cast<PointerType>(CI->getType())->getAddressSpace() ||
11169 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011170 IC.getTargetData().getTypeSizeInBits(DestPTy))
11171 return 0;
11172
11173 // Okay, we are casting from one integer or pointer type to another of
11174 // the same size. Instead of casting the pointer before
11175 // the store, cast the value to be stored.
11176 Value *NewCast;
11177 Value *SIOp0 = SI.getOperand(0);
11178 Instruction::CastOps opcode = Instruction::BitCast;
11179 const Type* CastSrcTy = SIOp0->getType();
11180 const Type* CastDstTy = SrcPTy;
11181 if (isa<PointerType>(CastDstTy)) {
11182 if (CastSrcTy->isInteger())
11183 opcode = Instruction::IntToPtr;
11184 } else if (isa<IntegerType>(CastDstTy)) {
11185 if (isa<PointerType>(SIOp0->getType()))
11186 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011187 }
Chris Lattner3914f722009-01-24 01:00:13 +000011188
11189 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11190 // emit a GEP to index into its first field.
11191 if (!NewGEPIndices.empty()) {
11192 if (Constant *C = dyn_cast<Constant>(CastOp))
11193 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11194 NewGEPIndices.size());
11195 else
11196 CastOp = IC.InsertNewInstBefore(
11197 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11198 NewGEPIndices.end()), SI);
11199 }
11200
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011201 if (Constant *C = dyn_cast<Constant>(SIOp0))
11202 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11203 else
11204 NewCast = IC.InsertNewInstBefore(
11205 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11206 SI);
11207 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011208}
11209
Chris Lattner4aebaee2008-11-27 08:56:30 +000011210/// equivalentAddressValues - Test if A and B will obviously have the same
11211/// value. This includes recognizing that %t0 and %t1 will have the same
11212/// value in code like this:
11213/// %t0 = getelementptr @a, 0, 3
11214/// store i32 0, i32* %t0
11215/// %t1 = getelementptr @a, 0, 3
11216/// %t2 = load i32* %t1
11217///
11218static bool equivalentAddressValues(Value *A, Value *B) {
11219 // Test if the values are trivially equivalent.
11220 if (A == B) return true;
11221
11222 // Test if the values come form identical arithmetic instructions.
11223 if (isa<BinaryOperator>(A) ||
11224 isa<CastInst>(A) ||
11225 isa<PHINode>(A) ||
11226 isa<GetElementPtrInst>(A))
11227 if (Instruction *BI = dyn_cast<Instruction>(B))
11228 if (cast<Instruction>(A)->isIdenticalTo(BI))
11229 return true;
11230
11231 // Otherwise they may not be equivalent.
11232 return false;
11233}
11234
Chris Lattner2f503e62005-01-31 05:36:43 +000011235Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11236 Value *Val = SI.getOperand(0);
11237 Value *Ptr = SI.getOperand(1);
11238
11239 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011240 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011241 ++NumCombined;
11242 return 0;
11243 }
Chris Lattner836692d2007-01-15 06:51:56 +000011244
11245 // If the RHS is an alloca with a single use, zapify the store, making the
11246 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011247 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011248 if (isa<AllocaInst>(Ptr)) {
11249 EraseInstFromFunction(SI);
11250 ++NumCombined;
11251 return 0;
11252 }
11253
11254 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11255 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11256 GEP->getOperand(0)->hasOneUse()) {
11257 EraseInstFromFunction(SI);
11258 ++NumCombined;
11259 return 0;
11260 }
11261 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011262
Dan Gohman9941f742007-07-20 16:34:21 +000011263 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011264 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11265 if (KnownAlign >
11266 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11267 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011268 SI.setAlignment(KnownAlign);
11269
Chris Lattner9ca96412006-02-08 03:25:32 +000011270 // Do really simple DSE, to catch cases where there are several consequtive
11271 // stores to the same location, separated by a few arithmetic operations. This
11272 // situation often occurs with bitfield accesses.
11273 BasicBlock::iterator BBI = &SI;
11274 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11275 --ScanInsts) {
11276 --BBI;
11277
11278 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11279 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011280 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11281 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011282 ++NumDeadStore;
11283 ++BBI;
11284 EraseInstFromFunction(*PrevSI);
11285 continue;
11286 }
11287 break;
11288 }
11289
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011290 // If this is a load, we have to stop. However, if the loaded value is from
11291 // the pointer we're loading and is producing the pointer we're storing,
11292 // then *this* store is dead (X = load P; store X -> P).
11293 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011294 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11295 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011296 EraseInstFromFunction(SI);
11297 ++NumCombined;
11298 return 0;
11299 }
11300 // Otherwise, this is a load from some other location. Stores before it
11301 // may not be dead.
11302 break;
11303 }
11304
Chris Lattner9ca96412006-02-08 03:25:32 +000011305 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011306 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011307 break;
11308 }
11309
11310
11311 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011312
11313 // store X, null -> turns into 'unreachable' in SimplifyCFG
11314 if (isa<ConstantPointerNull>(Ptr)) {
11315 if (!isa<UndefValue>(Val)) {
11316 SI.setOperand(0, UndefValue::get(Val->getType()));
11317 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011318 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011319 ++NumCombined;
11320 }
11321 return 0; // Do not modify these!
11322 }
11323
11324 // store undef, Ptr -> noop
11325 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011326 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011327 ++NumCombined;
11328 return 0;
11329 }
11330
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011331 // If the pointer destination is a cast, see if we can fold the cast into the
11332 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011333 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011334 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11335 return Res;
11336 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011337 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011338 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11339 return Res;
11340
Chris Lattner408902b2005-09-12 23:23:25 +000011341
11342 // If this store is the last instruction in the basic block, and if the block
11343 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011344 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011345 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011346 if (BI->isUnconditional())
11347 if (SimplifyStoreAtEndOfBlock(SI))
11348 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011349
Chris Lattner2f503e62005-01-31 05:36:43 +000011350 return 0;
11351}
11352
Chris Lattner3284d1f2007-04-15 00:07:55 +000011353/// SimplifyStoreAtEndOfBlock - Turn things like:
11354/// if () { *P = v1; } else { *P = v2 }
11355/// into a phi node with a store in the successor.
11356///
Chris Lattner31755a02007-04-15 01:02:18 +000011357/// Simplify things like:
11358/// *P = v1; if () { *P = v2; }
11359/// into a phi node with a store in the successor.
11360///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011361bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11362 BasicBlock *StoreBB = SI.getParent();
11363
11364 // Check to see if the successor block has exactly two incoming edges. If
11365 // so, see if the other predecessor contains a store to the same location.
11366 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011367 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011368
11369 // Determine whether Dest has exactly two predecessors and, if so, compute
11370 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011371 pred_iterator PI = pred_begin(DestBB);
11372 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011373 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011374 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011375 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011376 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011377 return false;
11378
11379 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011380 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011381 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011382 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011383 }
Chris Lattner31755a02007-04-15 01:02:18 +000011384 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011385 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011386
11387 // Bail out if all the relevant blocks aren't distinct (this can happen,
11388 // for example, if SI is in an infinite loop)
11389 if (StoreBB == DestBB || OtherBB == DestBB)
11390 return false;
11391
Chris Lattner31755a02007-04-15 01:02:18 +000011392 // Verify that the other block ends in a branch and is not otherwise empty.
11393 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011394 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011395 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011396 return false;
11397
Chris Lattner31755a02007-04-15 01:02:18 +000011398 // If the other block ends in an unconditional branch, check for the 'if then
11399 // else' case. there is an instruction before the branch.
11400 StoreInst *OtherStore = 0;
11401 if (OtherBr->isUnconditional()) {
11402 // If this isn't a store, or isn't a store to the same location, bail out.
11403 --BBI;
11404 OtherStore = dyn_cast<StoreInst>(BBI);
11405 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11406 return false;
11407 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011408 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011409 // destinations is StoreBB, then we have the if/then case.
11410 if (OtherBr->getSuccessor(0) != StoreBB &&
11411 OtherBr->getSuccessor(1) != StoreBB)
11412 return false;
11413
11414 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011415 // if/then triangle. See if there is a store to the same ptr as SI that
11416 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011417 for (;; --BBI) {
11418 // Check to see if we find the matching store.
11419 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11420 if (OtherStore->getOperand(1) != SI.getOperand(1))
11421 return false;
11422 break;
11423 }
Eli Friedman6903a242008-06-13 22:02:12 +000011424 // If we find something that may be using or overwriting the stored
11425 // value, or if we run out of instructions, we can't do the xform.
11426 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011427 BBI == OtherBB->begin())
11428 return false;
11429 }
11430
11431 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011432 // make sure nothing reads or overwrites the stored value in
11433 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011434 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11435 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011436 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011437 return false;
11438 }
11439 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011440
Chris Lattner31755a02007-04-15 01:02:18 +000011441 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011442 Value *MergedVal = OtherStore->getOperand(0);
11443 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011444 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011445 PN->reserveOperandSpace(2);
11446 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011447 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11448 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011449 }
11450
11451 // Advance to a place where it is safe to insert the new store and
11452 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011453 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011454 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11455 OtherStore->isVolatile()), *BBI);
11456
11457 // Nuke the old stores.
11458 EraseInstFromFunction(SI);
11459 EraseInstFromFunction(*OtherStore);
11460 ++NumCombined;
11461 return true;
11462}
11463
Chris Lattner2f503e62005-01-31 05:36:43 +000011464
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011465Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11466 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011467 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011468 BasicBlock *TrueDest;
11469 BasicBlock *FalseDest;
11470 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11471 !isa<Constant>(X)) {
11472 // Swap Destinations and condition...
11473 BI.setCondition(X);
11474 BI.setSuccessor(0, FalseDest);
11475 BI.setSuccessor(1, TrueDest);
11476 return &BI;
11477 }
11478
Reid Spencere4d87aa2006-12-23 06:05:41 +000011479 // Cannonicalize fcmp_one -> fcmp_oeq
11480 FCmpInst::Predicate FPred; Value *Y;
11481 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11482 TrueDest, FalseDest)))
11483 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11484 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11485 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011486 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011487 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11488 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011489 // Swap Destinations and condition...
11490 BI.setCondition(NewSCC);
11491 BI.setSuccessor(0, FalseDest);
11492 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011493 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011494 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011495 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011496 return &BI;
11497 }
11498
11499 // Cannonicalize icmp_ne -> icmp_eq
11500 ICmpInst::Predicate IPred;
11501 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11502 TrueDest, FalseDest)))
11503 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11504 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11505 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11506 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011507 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011508 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11509 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011510 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011511 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011512 BI.setSuccessor(0, FalseDest);
11513 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011514 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011515 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011516 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011517 return &BI;
11518 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011519
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011520 return 0;
11521}
Chris Lattner0864acf2002-11-04 16:18:53 +000011522
Chris Lattner46238a62004-07-03 00:26:11 +000011523Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11524 Value *Cond = SI.getCondition();
11525 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11526 if (I->getOpcode() == Instruction::Add)
11527 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11528 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11529 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011530 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011531 AddRHS));
11532 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011533 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011534 return &SI;
11535 }
11536 }
11537 return 0;
11538}
11539
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011540Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011541 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011542
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011543 if (!EV.hasIndices())
11544 return ReplaceInstUsesWith(EV, Agg);
11545
11546 if (Constant *C = dyn_cast<Constant>(Agg)) {
11547 if (isa<UndefValue>(C))
11548 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11549
11550 if (isa<ConstantAggregateZero>(C))
11551 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11552
11553 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11554 // Extract the element indexed by the first index out of the constant
11555 Value *V = C->getOperand(*EV.idx_begin());
11556 if (EV.getNumIndices() > 1)
11557 // Extract the remaining indices out of the constant indexed by the
11558 // first index
11559 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11560 else
11561 return ReplaceInstUsesWith(EV, V);
11562 }
11563 return 0; // Can't handle other constants
11564 }
11565 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11566 // We're extracting from an insertvalue instruction, compare the indices
11567 const unsigned *exti, *exte, *insi, *inse;
11568 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11569 exte = EV.idx_end(), inse = IV->idx_end();
11570 exti != exte && insi != inse;
11571 ++exti, ++insi) {
11572 if (*insi != *exti)
11573 // The insert and extract both reference distinctly different elements.
11574 // This means the extract is not influenced by the insert, and we can
11575 // replace the aggregate operand of the extract with the aggregate
11576 // operand of the insert. i.e., replace
11577 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11578 // %E = extractvalue { i32, { i32 } } %I, 0
11579 // with
11580 // %E = extractvalue { i32, { i32 } } %A, 0
11581 return ExtractValueInst::Create(IV->getAggregateOperand(),
11582 EV.idx_begin(), EV.idx_end());
11583 }
11584 if (exti == exte && insi == inse)
11585 // Both iterators are at the end: Index lists are identical. Replace
11586 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11587 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11588 // with "i32 42"
11589 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11590 if (exti == exte) {
11591 // The extract list is a prefix of the insert list. i.e. replace
11592 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11593 // %E = extractvalue { i32, { i32 } } %I, 1
11594 // with
11595 // %X = extractvalue { i32, { i32 } } %A, 1
11596 // %E = insertvalue { i32 } %X, i32 42, 0
11597 // by switching the order of the insert and extract (though the
11598 // insertvalue should be left in, since it may have other uses).
11599 Value *NewEV = InsertNewInstBefore(
11600 ExtractValueInst::Create(IV->getAggregateOperand(),
11601 EV.idx_begin(), EV.idx_end()),
11602 EV);
11603 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11604 insi, inse);
11605 }
11606 if (insi == inse)
11607 // The insert list is a prefix of the extract list
11608 // We can simply remove the common indices from the extract and make it
11609 // operate on the inserted value instead of the insertvalue result.
11610 // i.e., replace
11611 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11612 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11613 // with
11614 // %E extractvalue { i32 } { i32 42 }, 0
11615 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11616 exti, exte);
11617 }
11618 // Can't simplify extracts from other values. Note that nested extracts are
11619 // already simplified implicitely by the above (extract ( extract (insert) )
11620 // will be translated into extract ( insert ( extract ) ) first and then just
11621 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011622 return 0;
11623}
11624
Chris Lattner220b0cf2006-03-05 00:22:33 +000011625/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11626/// is to leave as a vector operation.
11627static bool CheapToScalarize(Value *V, bool isConstant) {
11628 if (isa<ConstantAggregateZero>(V))
11629 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011630 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011631 if (isConstant) return true;
11632 // If all elts are the same, we can extract.
11633 Constant *Op0 = C->getOperand(0);
11634 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11635 if (C->getOperand(i) != Op0)
11636 return false;
11637 return true;
11638 }
11639 Instruction *I = dyn_cast<Instruction>(V);
11640 if (!I) return false;
11641
11642 // Insert element gets simplified to the inserted element or is deleted if
11643 // this is constant idx extract element and its a constant idx insertelt.
11644 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11645 isa<ConstantInt>(I->getOperand(2)))
11646 return true;
11647 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11648 return true;
11649 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11650 if (BO->hasOneUse() &&
11651 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11652 CheapToScalarize(BO->getOperand(1), isConstant)))
11653 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011654 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11655 if (CI->hasOneUse() &&
11656 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11657 CheapToScalarize(CI->getOperand(1), isConstant)))
11658 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011659
11660 return false;
11661}
11662
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011663/// Read and decode a shufflevector mask.
11664///
11665/// It turns undef elements into values that are larger than the number of
11666/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011667static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11668 unsigned NElts = SVI->getType()->getNumElements();
11669 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11670 return std::vector<unsigned>(NElts, 0);
11671 if (isa<UndefValue>(SVI->getOperand(2)))
11672 return std::vector<unsigned>(NElts, 2*NElts);
11673
11674 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011675 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011676 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11677 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011678 Result.push_back(NElts*2); // undef -> 8
11679 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011680 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011681 return Result;
11682}
11683
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011684/// FindScalarElement - Given a vector and an element number, see if the scalar
11685/// value is already around as a register, for example if it were inserted then
11686/// extracted from the vector.
11687static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011688 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11689 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011690 unsigned Width = PTy->getNumElements();
11691 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011692 return UndefValue::get(PTy->getElementType());
11693
11694 if (isa<UndefValue>(V))
11695 return UndefValue::get(PTy->getElementType());
11696 else if (isa<ConstantAggregateZero>(V))
11697 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011698 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011699 return CP->getOperand(EltNo);
11700 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11701 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011702 if (!isa<ConstantInt>(III->getOperand(2)))
11703 return 0;
11704 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011705
11706 // If this is an insert to the element we are looking for, return the
11707 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011708 if (EltNo == IIElt)
11709 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011710
11711 // Otherwise, the insertelement doesn't modify the value, recurse on its
11712 // vector input.
11713 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011714 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011715 unsigned LHSWidth =
11716 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011717 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011718 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011719 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011720 else if (InEl < LHSWidth*2)
11721 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011722 else
11723 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011724 }
11725
11726 // Otherwise, we don't know.
11727 return 0;
11728}
11729
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011730Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011731 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011732 if (isa<UndefValue>(EI.getOperand(0)))
11733 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11734
Dan Gohman07a96762007-07-16 14:29:03 +000011735 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011736 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11737 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11738
Reid Spencer9d6565a2007-02-15 02:26:10 +000011739 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011740 // If vector val is constant with all elements the same, replace EI with
11741 // that element. When the elements are not identical, we cannot replace yet
11742 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011743 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011744 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011745 if (C->getOperand(i) != op0) {
11746 op0 = 0;
11747 break;
11748 }
11749 if (op0)
11750 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011751 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011752
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011753 // If extracting a specified index from the vector, see if we can recursively
11754 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011755 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011756 unsigned IndexVal = IdxC->getZExtValue();
11757 unsigned VectorWidth =
11758 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11759
11760 // If this is extracting an invalid index, turn this into undef, to avoid
11761 // crashing the code below.
11762 if (IndexVal >= VectorWidth)
11763 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11764
Chris Lattner867b99f2006-10-05 06:55:50 +000011765 // This instruction only demands the single element from the input vector.
11766 // If the input vector has a single use, simplify it based on this use
11767 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011768 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011769 uint64_t UndefElts;
11770 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011771 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011772 UndefElts)) {
11773 EI.setOperand(0, V);
11774 return &EI;
11775 }
11776 }
11777
Reid Spencerb83eb642006-10-20 07:07:24 +000011778 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011779 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011780
11781 // If the this extractelement is directly using a bitcast from a vector of
11782 // the same number of elements, see if we can find the source element from
11783 // it. In this case, we will end up needing to bitcast the scalars.
11784 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11785 if (const VectorType *VT =
11786 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11787 if (VT->getNumElements() == VectorWidth)
11788 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11789 return new BitCastInst(Elt, EI.getType());
11790 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011791 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011792
Chris Lattner73fa49d2006-05-25 22:53:38 +000011793 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011794 if (I->hasOneUse()) {
11795 // Push extractelement into predecessor operation if legal and
11796 // profitable to do so
11797 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011798 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11799 if (CheapToScalarize(BO, isConstantElt)) {
11800 ExtractElementInst *newEI0 =
11801 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11802 EI.getName()+".lhs");
11803 ExtractElementInst *newEI1 =
11804 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11805 EI.getName()+".rhs");
11806 InsertNewInstBefore(newEI0, EI);
11807 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011808 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011809 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011810 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011811 unsigned AS =
11812 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011813 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11814 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011815 GetElementPtrInst *GEP =
11816 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011817 InsertNewInstBefore(GEP, EI);
11818 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011819 }
11820 }
11821 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11822 // Extracting the inserted element?
11823 if (IE->getOperand(2) == EI.getOperand(1))
11824 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11825 // If the inserted and extracted elements are constants, they must not
11826 // be the same value, extract from the pre-inserted value instead.
11827 if (isa<Constant>(IE->getOperand(2)) &&
11828 isa<Constant>(EI.getOperand(1))) {
11829 AddUsesToWorkList(EI);
11830 EI.setOperand(0, IE->getOperand(0));
11831 return &EI;
11832 }
11833 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11834 // If this is extracting an element from a shufflevector, figure out where
11835 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011836 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11837 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011838 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011839 unsigned LHSWidth =
11840 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11841
11842 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011843 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011844 else if (SrcIdx < LHSWidth*2) {
11845 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011846 Src = SVI->getOperand(1);
11847 } else {
11848 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011849 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011850 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011851 }
11852 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011853 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011854 return 0;
11855}
11856
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011857/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11858/// elements from either LHS or RHS, return the shuffle mask and true.
11859/// Otherwise, return false.
11860static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11861 std::vector<Constant*> &Mask) {
11862 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11863 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011864 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011865
11866 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011867 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011868 return true;
11869 } else if (V == LHS) {
11870 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011871 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011872 return true;
11873 } else if (V == RHS) {
11874 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011875 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011876 return true;
11877 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11878 // If this is an insert of an extract from some other vector, include it.
11879 Value *VecOp = IEI->getOperand(0);
11880 Value *ScalarOp = IEI->getOperand(1);
11881 Value *IdxOp = IEI->getOperand(2);
11882
Chris Lattnerd929f062006-04-27 21:14:21 +000011883 if (!isa<ConstantInt>(IdxOp))
11884 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011885 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011886
11887 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11888 // Okay, we can handle this if the vector we are insertinting into is
11889 // transitively ok.
11890 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11891 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011892 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011893 return true;
11894 }
11895 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11896 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011897 EI->getOperand(0)->getType() == V->getType()) {
11898 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011899 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011900
11901 // This must be extracting from either LHS or RHS.
11902 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11903 // Okay, we can handle this if the vector we are insertinting into is
11904 // transitively ok.
11905 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11906 // If so, update the mask to reflect the inserted value.
11907 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011908 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011909 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011910 } else {
11911 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011912 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011913 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011914
11915 }
11916 return true;
11917 }
11918 }
11919 }
11920 }
11921 }
11922 // TODO: Handle shufflevector here!
11923
11924 return false;
11925}
11926
11927/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11928/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11929/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011930static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011931 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011932 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011933 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011934 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011935 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011936
11937 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011938 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011939 return V;
11940 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011941 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011942 return V;
11943 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11944 // If this is an insert of an extract from some other vector, include it.
11945 Value *VecOp = IEI->getOperand(0);
11946 Value *ScalarOp = IEI->getOperand(1);
11947 Value *IdxOp = IEI->getOperand(2);
11948
11949 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11950 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11951 EI->getOperand(0)->getType() == V->getType()) {
11952 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011953 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11954 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011955
11956 // Either the extracted from or inserted into vector must be RHSVec,
11957 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011958 if (EI->getOperand(0) == RHS || RHS == 0) {
11959 RHS = EI->getOperand(0);
11960 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011961 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011962 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011963 return V;
11964 }
11965
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011966 if (VecOp == RHS) {
11967 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011968 // Everything but the extracted element is replaced with the RHS.
11969 for (unsigned i = 0; i != NumElts; ++i) {
11970 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011971 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011972 }
11973 return V;
11974 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011975
11976 // If this insertelement is a chain that comes from exactly these two
11977 // vectors, return the vector and the effective shuffle.
11978 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11979 return EI->getOperand(0);
11980
Chris Lattnerefb47352006-04-15 01:39:45 +000011981 }
11982 }
11983 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011984 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011985
11986 // Otherwise, can't do anything fancy. Return an identity vector.
11987 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011988 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011989 return V;
11990}
11991
11992Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11993 Value *VecOp = IE.getOperand(0);
11994 Value *ScalarOp = IE.getOperand(1);
11995 Value *IdxOp = IE.getOperand(2);
11996
Chris Lattner599ded12007-04-09 01:11:16 +000011997 // Inserting an undef or into an undefined place, remove this.
11998 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11999 ReplaceInstUsesWith(IE, VecOp);
12000
Chris Lattnerefb47352006-04-15 01:39:45 +000012001 // If the inserted element was extracted from some other vector, and if the
12002 // indexes are constant, try to turn this into a shufflevector operation.
12003 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12004 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12005 EI->getOperand(0)->getType() == IE.getType()) {
12006 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012007 unsigned ExtractedIdx =
12008 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012009 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012010
12011 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12012 return ReplaceInstUsesWith(IE, VecOp);
12013
12014 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12015 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12016
12017 // If we are extracting a value from a vector, then inserting it right
12018 // back into the same place, just use the input vector.
12019 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12020 return ReplaceInstUsesWith(IE, VecOp);
12021
12022 // We could theoretically do this for ANY input. However, doing so could
12023 // turn chains of insertelement instructions into a chain of shufflevector
12024 // instructions, and right now we do not merge shufflevectors. As such,
12025 // only do this in a situation where it is clear that there is benefit.
12026 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12027 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12028 // the values of VecOp, except then one read from EIOp0.
12029 // Build a new shuffle mask.
12030 std::vector<Constant*> Mask;
12031 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012032 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012033 else {
12034 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012035 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012036 NumVectorElts));
12037 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012038 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012039 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012040 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012041 }
12042
12043 // If this insertelement isn't used by some other insertelement, turn it
12044 // (and any insertelements it points to), into one big shuffle.
12045 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12046 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012047 Value *RHS = 0;
12048 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12049 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12050 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012051 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012052 }
12053 }
12054 }
12055
12056 return 0;
12057}
12058
12059
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012060Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12061 Value *LHS = SVI.getOperand(0);
12062 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012063 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012064
12065 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012066
Chris Lattner867b99f2006-10-05 06:55:50 +000012067 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012068 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012069 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012070
12071 uint64_t UndefElts;
12072 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012073
12074 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12075 return 0;
12076
Dan Gohman488fbfc2008-09-09 18:11:14 +000012077 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12078 if (VWidth <= 64 &&
Dan Gohman3139ff82008-09-11 22:47:57 +000012079 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12080 LHS = SVI.getOperand(0);
12081 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012082 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012083 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012084
Chris Lattner863bcff2006-05-25 23:48:38 +000012085 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12086 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12087 if (LHS == RHS || isa<UndefValue>(LHS)) {
12088 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012089 // shuffle(undef,undef,mask) -> undef.
12090 return ReplaceInstUsesWith(SVI, LHS);
12091 }
12092
Chris Lattner863bcff2006-05-25 23:48:38 +000012093 // Remap any references to RHS to use LHS.
12094 std::vector<Constant*> Elts;
12095 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012096 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012097 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012098 else {
12099 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012100 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012101 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012102 Elts.push_back(UndefValue::get(Type::Int32Ty));
12103 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012104 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012105 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12106 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012107 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012108 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012109 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012110 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012111 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012112 LHS = SVI.getOperand(0);
12113 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012114 MadeChange = true;
12115 }
12116
Chris Lattner7b2e27922006-05-26 00:29:06 +000012117 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012118 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012119
Chris Lattner863bcff2006-05-25 23:48:38 +000012120 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12121 if (Mask[i] >= e*2) continue; // Ignore undef values.
12122 // Is this an identity shuffle of the LHS value?
12123 isLHSID &= (Mask[i] == i);
12124
12125 // Is this an identity shuffle of the RHS value?
12126 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012127 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012128
Chris Lattner863bcff2006-05-25 23:48:38 +000012129 // Eliminate identity shuffles.
12130 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12131 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012132
Chris Lattner7b2e27922006-05-26 00:29:06 +000012133 // If the LHS is a shufflevector itself, see if we can combine it with this
12134 // one without producing an unusual shuffle. Here we are really conservative:
12135 // we are absolutely afraid of producing a shuffle mask not in the input
12136 // program, because the code gen may not be smart enough to turn a merged
12137 // shuffle into two specific shuffles: it may produce worse code. As such,
12138 // we only merge two shuffles if the result is one of the two input shuffle
12139 // masks. In this case, merging the shuffles just removes one instruction,
12140 // which we know is safe. This is good for things like turning:
12141 // (splat(splat)) -> splat.
12142 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12143 if (isa<UndefValue>(RHS)) {
12144 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12145
12146 std::vector<unsigned> NewMask;
12147 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12148 if (Mask[i] >= 2*e)
12149 NewMask.push_back(2*e);
12150 else
12151 NewMask.push_back(LHSMask[Mask[i]]);
12152
12153 // If the result mask is equal to the src shuffle or this shuffle mask, do
12154 // the replacement.
12155 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012156 unsigned LHSInNElts =
12157 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012158 std::vector<Constant*> Elts;
12159 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012160 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012161 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012162 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012163 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012164 }
12165 }
12166 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12167 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012168 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012169 }
12170 }
12171 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012172
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012173 return MadeChange ? &SVI : 0;
12174}
12175
12176
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012177
Chris Lattnerea1c4542004-12-08 23:43:58 +000012178
12179/// TryToSinkInstruction - Try to move the specified instruction from its
12180/// current block into the beginning of DestBlock, which can only happen if it's
12181/// safe to move the instruction past all of the instructions between it and the
12182/// end of its block.
12183static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12184 assert(I->hasOneUse() && "Invariants didn't hold!");
12185
Chris Lattner108e9022005-10-27 17:13:11 +000012186 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012187 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12188 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012189
Chris Lattnerea1c4542004-12-08 23:43:58 +000012190 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012191 if (isa<AllocaInst>(I) && I->getParent() ==
12192 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012193 return false;
12194
Chris Lattner96a52a62004-12-09 07:14:34 +000012195 // We can only sink load instructions if there is nothing between the load and
12196 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012197 if (I->mayReadFromMemory()) {
12198 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012199 Scan != E; ++Scan)
12200 if (Scan->mayWriteToMemory())
12201 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012202 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012203
Dan Gohman02dea8b2008-05-23 21:05:58 +000012204 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012205
Chris Lattner4bc5f802005-08-08 19:11:57 +000012206 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012207 ++NumSunkInst;
12208 return true;
12209}
12210
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012211
12212/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12213/// all reachable code to the worklist.
12214///
12215/// This has a couple of tricks to make the code faster and more powerful. In
12216/// particular, we constant fold and DCE instructions as we go, to avoid adding
12217/// them to the worklist (this significantly speeds up instcombine on code where
12218/// many instructions are dead or constant). Additionally, if we find a branch
12219/// whose condition is a known constant, we only visit the reachable successors.
12220///
12221static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012222 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012223 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012224 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012225 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012226 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012227
Chris Lattner2c7718a2007-03-23 19:17:18 +000012228 while (!Worklist.empty()) {
12229 BB = Worklist.back();
12230 Worklist.pop_back();
12231
12232 // We have now visited this block! If we've already been here, ignore it.
12233 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012234
12235 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012236 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12237 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012238
Chris Lattner2c7718a2007-03-23 19:17:18 +000012239 // DCE instruction if trivially dead.
12240 if (isInstructionTriviallyDead(Inst)) {
12241 ++NumDeadInst;
12242 DOUT << "IC: DCE: " << *Inst;
12243 Inst->eraseFromParent();
12244 continue;
12245 }
12246
12247 // ConstantProp instruction if trivially constant.
12248 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12249 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12250 Inst->replaceAllUsesWith(C);
12251 ++NumConstProp;
12252 Inst->eraseFromParent();
12253 continue;
12254 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012255
Devang Patel7fe1dec2008-11-19 18:56:50 +000012256 // If there are two consecutive llvm.dbg.stoppoint calls then
12257 // it is likely that the optimizer deleted code in between these
12258 // two intrinsics.
12259 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12260 if (DBI_Next) {
12261 if (DBI_Prev
12262 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12263 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12264 IC.RemoveFromWorkList(DBI_Prev);
12265 DBI_Prev->eraseFromParent();
12266 }
12267 DBI_Prev = DBI_Next;
12268 }
12269
Chris Lattner2c7718a2007-03-23 19:17:18 +000012270 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012271 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012272
12273 // Recursively visit successors. If this is a branch or switch on a
12274 // constant, only visit the reachable successor.
12275 TerminatorInst *TI = BB->getTerminator();
12276 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12277 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12278 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012279 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012280 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012281 continue;
12282 }
12283 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12284 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12285 // See if this is an explicit destination.
12286 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12287 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012288 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012289 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012290 continue;
12291 }
12292
12293 // Otherwise it is the default destination.
12294 Worklist.push_back(SI->getSuccessor(0));
12295 continue;
12296 }
12297 }
12298
12299 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12300 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012301 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012302}
12303
Chris Lattnerec9c3582007-03-03 02:04:50 +000012304bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012305 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012306 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012307
12308 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12309 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012310
Chris Lattnerb3d59702005-07-07 20:40:38 +000012311 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012312 // Do a depth-first traversal of the function, populate the worklist with
12313 // the reachable instructions. Ignore blocks that are not reachable. Keep
12314 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012315 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012316 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012317
Chris Lattnerb3d59702005-07-07 20:40:38 +000012318 // Do a quick scan over the function. If we find any blocks that are
12319 // unreachable, remove any instructions inside of them. This prevents
12320 // the instcombine code from having to deal with some bad special cases.
12321 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12322 if (!Visited.count(BB)) {
12323 Instruction *Term = BB->getTerminator();
12324 while (Term != BB->begin()) { // Remove instrs bottom-up
12325 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012326
Bill Wendlingb7427032006-11-26 09:46:52 +000012327 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012328 ++NumDeadInst;
12329
12330 if (!I->use_empty())
12331 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12332 I->eraseFromParent();
Chris Lattner1e19d602009-01-31 07:04:22 +000012333 Changed = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012334 }
12335 }
12336 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012337
Chris Lattnerdbab3862007-03-02 21:28:56 +000012338 while (!Worklist.empty()) {
12339 Instruction *I = RemoveOneFromWorkList();
12340 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012341
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012342 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012343 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012344 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012345 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012346 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012347 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012348
Bill Wendlingb7427032006-11-26 09:46:52 +000012349 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012350
12351 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012352 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012353 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012354 continue;
12355 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012356
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012357 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012358 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012359 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012360
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012361 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012362 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012363 ReplaceInstUsesWith(*I, C);
12364
Chris Lattner62b14df2002-09-02 04:59:56 +000012365 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012366 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012367 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012368 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012369 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012370 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012371
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012372 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12373 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012374 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012376 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012377 if (NewC != CE) {
12378 i->set(NewC);
12379 Changed = true;
12380 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012381 }
12382
Chris Lattnerea1c4542004-12-08 23:43:58 +000012383 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012384 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012385 BasicBlock *BB = I->getParent();
12386 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12387 if (UserParent != BB) {
12388 bool UserIsSuccessor = false;
12389 // See if the user is one of our successors.
12390 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12391 if (*SI == UserParent) {
12392 UserIsSuccessor = true;
12393 break;
12394 }
12395
12396 // If the user is one of our immediate successors, and if that successor
12397 // only has us as a predecessors (we'd have to split the critical edge
12398 // otherwise), we can keep going.
12399 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12400 next(pred_begin(UserParent)) == pred_end(UserParent))
12401 // Okay, the CFG is simple enough, try to sink this instruction.
12402 Changed |= TryToSinkInstruction(I, UserParent);
12403 }
12404 }
12405
Chris Lattner8a2a3112001-12-14 16:52:21 +000012406 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012407#ifndef NDEBUG
12408 std::string OrigI;
12409#endif
12410 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012411 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012412 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012413 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012414 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012415 DOUT << "IC: Old = " << *I
12416 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012417
Chris Lattnerf523d062004-06-09 05:08:07 +000012418 // Everything uses the new instruction now.
12419 I->replaceAllUsesWith(Result);
12420
12421 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012422 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012423 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012424
Chris Lattner6934a042007-02-11 01:23:03 +000012425 // Move the name to the new instruction first.
12426 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012427
12428 // Insert the new instruction into the basic block...
12429 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012430 BasicBlock::iterator InsertPos = I;
12431
12432 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12433 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12434 ++InsertPos;
12435
12436 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012437
Chris Lattner00d51312004-05-01 23:27:23 +000012438 // Make sure that we reprocess all operands now that we reduced their
12439 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012440 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012441
Chris Lattnerf523d062004-06-09 05:08:07 +000012442 // Instructions can end up on the worklist more than once. Make sure
12443 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012444 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012445
12446 // Erase the old instruction.
12447 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012448 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012449#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012450 DOUT << "IC: Mod = " << OrigI
12451 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012452#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012453
Chris Lattner90ac28c2002-08-02 19:29:35 +000012454 // If the instruction was modified, it's possible that it is now dead.
12455 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012456 if (isInstructionTriviallyDead(I)) {
12457 // Make sure we process all operands now that we are reducing their
12458 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012459 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012460
Chris Lattner00d51312004-05-01 23:27:23 +000012461 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012462 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012463 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012464 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012465 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012466 AddToWorkList(I);
12467 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012468 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012469 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012470 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012471 }
12472 }
12473
Chris Lattnerec9c3582007-03-03 02:04:50 +000012474 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012475
12476 // Do an explicit clear, this shrinks the map if needed.
12477 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012478 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012479}
12480
Chris Lattnerec9c3582007-03-03 02:04:50 +000012481
12482bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012483 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12484
Chris Lattnerec9c3582007-03-03 02:04:50 +000012485 bool EverMadeChange = false;
12486
12487 // Iterate while there is work to do.
12488 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012489 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012490 EverMadeChange = true;
12491 return EverMadeChange;
12492}
12493
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012494FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012495 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012496}