blob: c5f4dea0f0f3bd9ba257d61fdce8ca1397fef56c [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 Lattnerdbab3862007-03-02 21:28:56 +000077 std::vector<Instruction*> Worklist;
78 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
Devang Patel794fd752007-05-01 21:15:47 +000083 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
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 Lattner7e708292002-06-25 16:13:24 +0000183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *LHS,
197 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000200
Reid Spencere4d87aa2006-12-23 06:05:41 +0000201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000204 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000207 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000211 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000218 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000222 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000223 Instruction *visitCallInst(CallInst &CI);
224 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000225 Instruction *visitPHINode(PHINode &PN);
226 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000227 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000228 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000229 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000230 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000231 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000232 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000233 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000234 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000235 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000236 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000237
238 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000240
Chris Lattner9fe38862003-06-19 17:00:31 +0000241 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000242 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000243 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000244 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000245 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000247 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248
Chris Lattner28977af2004-04-05 01:30:19 +0000249 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000250 // InsertNewInstBefore - insert an instruction New before instruction Old
251 // in the program. Add the new instruction to the worklist.
252 //
Chris Lattner955f3312004-09-28 21:48:02 +0000253 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000254 assert(New && New->getParent() == 0 &&
255 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000256 BasicBlock *BB = Old.getParent();
257 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000258 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000259 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000260 }
261
Chris Lattner0c967662004-09-24 15:21:34 +0000262 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263 /// This also adds the cast to the worklist. Finally, this returns the
264 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000265 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000267 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000268
Chris Lattnere2ed0572006-04-06 19:19:17 +0000269 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000270 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000271
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000272 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000274 return C;
275 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000276
277 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281
Chris Lattner8b170942002-08-09 23:47:40 +0000282 // ReplaceInstUsesWith - This method is to be used when an instruction is
283 // found to be dead, replacable with another preexisting expression. Here
284 // we add all uses of I to the worklist, replace all uses of I with the new
285 // value, then return I, so that the inst combiner will know that I was
286 // modified.
287 //
288 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000289 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000290 if (&I != V) {
291 I.replaceAllUsesWith(V);
292 return &I;
293 } else {
294 // If we are replacing the instruction with itself, this must be in a
295 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000296 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000297 return &I;
298 }
Chris Lattner8b170942002-08-09 23:47:40 +0000299 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300
Chris Lattner6dce1a72006-02-07 06:56:34 +0000301 // UpdateValueUsesWith - This method is to be used when an value is
302 // found to be replacable with another preexisting expression or was
303 // updated. Here we add all uses of I to the worklist, replace all uses of
304 // I with the new value (unless the instruction was just updated), then
305 // return true, so that the inst combiner will know that I was modified.
306 //
307 bool UpdateValueUsesWith(Value *Old, Value *New) {
308 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
309 if (Old != New)
310 Old->replaceAllUsesWith(New);
311 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000312 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000313 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000314 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000315 return true;
316 }
317
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
321 // this function.
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000325 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000326 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000327 return 0; // Don't do anything with FI
328 }
Chris Lattner173234a2008-06-02 01:18:21 +0000329
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 }
334
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 }
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000342
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000343 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000344 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345 /// InsertBefore instruction. This is specialized a bit to avoid inserting
346 /// casts that are known to not do anything...
347 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000348 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000350 Instruction *InsertBefore);
351
Reid Spencere4d87aa2006-12-23 06:05:41 +0000352 /// SimplifyCommutative - This performs a few simplifications for
353 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000354 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000355
Reid Spencere4d87aa2006-12-23 06:05:41 +0000356 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357 /// most-complex to least-complex order.
358 bool SimplifyCompare(CmpInst &I);
359
Reid Spencer2ec619a2007-03-23 21:24:59 +0000360 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000362 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
363 APInt& KnownZero, APInt& KnownOne,
364 unsigned Depth = 0);
365
Chris Lattner867b99f2006-10-05 06:55:50 +0000366 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367 uint64_t &UndefElts, unsigned Depth = 0);
368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379
380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398 unsigned CastOpc,
399 int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000412static unsigned getComplexity(Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000415 return 3;
416 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000417 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000420}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000421
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422// isOnlyUse - Return true if this instruction will be deleted if we stop using
423// it.
424static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000425 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426}
427
Chris Lattner4cb170c2004-02-23 06:38:22 +0000428// getPromotedType - Return the specified type promoted as it would be to pass
429// though a va_arg area...
430static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000434 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000435 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000436}
437
Reid Spencer3da59db2006-11-27 01:05:10 +0000438/// getBitCastOperand - If the specified operand is a CastInst or a constant
439/// expression bitcast, return the operand value, otherwise return null.
440static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000442 return I->getOperand(0);
443 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000444 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000445 return CE->getOperand(0);
446 return 0;
447}
448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449/// This function is a wrapper around CastInst::isEliminableCastPair. It
450/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000451static Instruction::CastOps
452isEliminableCastPair(
453 const CastInst *CI, ///< The first cast instruction
454 unsigned opcode, ///< The opcode of the second cast instruction
455 const Type *DstTy, ///< The target type for the second cast instruction
456 TargetData *TD ///< The target data for pointer size
457) {
458
459 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
460 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000461
Reid Spencer3da59db2006-11-27 01:05:10 +0000462 // Get the opcodes of the two Cast instructions
463 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 return Instruction::CastOps(
467 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000469}
470
471/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472/// in any code being generated. It does not require codegen if V is simple
473/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000474static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
475 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000476 if (V->getType() == Ty || isa<Constant>(V)) return false;
477
Chris Lattner01575b72006-05-25 23:24:33 +0000478 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000479 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000480 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000481 return false;
482 return true;
483}
484
485/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486/// InsertBefore instruction. This is specialized a bit to avoid inserting
487/// casts that are known to not do anything...
488///
Reid Spencer17212df2006-12-12 09:18:51 +0000489Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000491 Instruction *InsertBefore) {
492 if (V->getType() == DestTy) return V;
493 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000494 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000495
Reid Spencer17212df2006-12-12 09:18:51 +0000496 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000497}
498
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// SimplifyCommutative - This performs a few simplifications for commutative
500// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000501//
Chris Lattner4f98c562003-03-10 21:43:22 +0000502// 1. Order operands such that they are listed from right (least complex) to
503// left (most complex). This puts constants before unary operators before
504// binary operators.
505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000508//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 bool Changed = false;
511 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
524 return true;
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000532 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 Op1->getOperand(0),
535 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000536 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
539 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000543}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000544
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545/// SimplifyCompare - For a CmpInst this function just orders the operands
546/// so that theyare listed from right (least complex) to left (most complex).
547/// This puts constants before unary operators before binary operators.
548bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
550 return false;
551 I.swapOperands();
552 // Compare instructions are not associative so there's nothing else we can do.
553 return true;
554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000558//
Chris Lattner8d969642003-03-10 23:06:50 +0000559static inline Value *dyn_castNegVal(Value *V) {
560 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000561 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000562
Chris Lattner0ce85802004-12-14 20:08:06 +0000563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000566
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
569 return ConstantExpr::getNeg(C);
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000572}
573
Chris Lattner8d969642003-03-10 23:06:50 +0000574static inline Value *dyn_castNotVal(Value *V) {
575 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000576 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000577
578 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000580 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000581 return 0;
582}
583
Chris Lattnerc8802d22003-03-11 00:12:48 +0000584// dyn_castFoldableMul - If this value is a multiply that can be folded into
585// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000586// non-constant operand of the multiply, and set CST to point to the multiplier.
587// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000588//
Chris Lattner50af16a2004-11-13 19:50:12 +0000589static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000590 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000591 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000592 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000594 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000595 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000596 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000597 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000598 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000599 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000600 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000601 return I->getOperand(0);
602 }
603 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000605}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000606
Chris Lattner574da9b2005-01-13 20:14:25 +0000607/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608/// expression, return it.
609static User *dyn_castGetElementPtr(Value *V) {
610 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612 if (CE->getOpcode() == Instruction::GetElementPtr)
613 return cast<User>(V);
614 return false;
615}
616
Dan Gohmaneee962e2008-04-10 18:43:06 +0000617/// getOpcode - If this is an Instruction or a ConstantExpr, return the
618/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000619static unsigned getOpcode(const Value *V) {
620 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000621 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000622 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000623 return CE->getOpcode();
624 // Use UserOp1 to mean there's no opcode.
625 return Instruction::UserOp1;
626}
627
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000632}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000633/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000634static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000635 APInt Val(C->getValue());
636 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000637}
638/// Add - Add two ConstantInts together
639static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() + C2->getValue());
641}
642/// And - Bitwise AND two ConstantInts together
643static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() & C2->getValue());
645}
646/// Subtract - Subtract one ConstantInt from another
647static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() - C2->getValue());
649}
650/// Multiply - Multiply two ConstantInts together
651static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000653}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000654/// MultiplyOverflows - True if the multiply can not be expressed in an int
655/// this size.
656static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659 if (sign) {
660 LHSExt.sext(W * 2);
661 RHSExt.sext(W * 2);
662 } else {
663 LHSExt.zext(W * 2);
664 RHSExt.zext(W * 2);
665 }
666
667 APInt MulExt = LHSExt * RHSExt;
668
669 if (sign) {
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
673 } else
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675}
Chris Lattner955f3312004-09-28 21:48:02 +0000676
Reid Spencere7816b52007-03-08 01:52:58 +0000677
Chris Lattner255d8912006-02-11 09:31:47 +0000678/// ShrinkDemandedConstant - Check to see if the specified operand of the
679/// specified instruction is a constant integer. If so, check to see if there
680/// are any bits set in the constant that are not demanded. If so, shrink the
681/// constant and return true.
682static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000683 APInt Demanded) {
684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
690
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
694 return false;
695
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
698 I->setOperand(OpNo, ConstantInt::get(Demanded));
699 return true;
700}
701
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703// set of known zero and one bits, compute the maximum and minimum values that
704// could have the specified known zero and known one bits, returning them in
705// min/max.
706static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000707 const APInt& KnownZero,
708 const APInt& KnownOne,
709 APInt& Min, APInt& Max) {
710 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711 assert(KnownZero.getBitWidth() == BitWidth &&
712 KnownOne.getBitWidth() == BitWidth &&
713 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000715 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
719 Min = KnownOne;
720 Max = KnownOne|UnknownBits;
721
Zhou Sheng4acf1552007-03-28 05:15:57 +0000722 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000723 Min.set(BitWidth-1);
724 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726}
727
728// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729// a set of known zero and one bits, compute the maximum and minimum values that
730// could have the specified known zero and known one bits, returning them in
731// min/max.
732static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000733 const APInt &KnownZero,
734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
736 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000737 assert(KnownZero.getBitWidth() == BitWidth &&
738 KnownOne.getBitWidth() == BitWidth &&
739 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000741 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000742
743 // The minimum value is when the unknown bits are all zeros.
744 Min = KnownOne;
745 // The maximum value is when the unknown bits are all ones.
746 Max = KnownOne|UnknownBits;
747}
Chris Lattner255d8912006-02-11 09:31:47 +0000748
Reid Spencer8cb68342007-03-12 17:25:59 +0000749/// SimplifyDemandedBits - This function attempts to replace V with a simpler
750/// value based on the demanded bits. When this function is called, it is known
751/// that only the bits set in DemandedMask of the result of V are ever used
752/// downstream. Consequently, depending on the mask and V, it may be possible
753/// to replace V with a constant or one of its operands. In such cases, this
754/// function does the replacement and returns true. In all other cases, it
755/// returns false after analyzing the expression and setting KnownOne and known
756/// to be one in the expression. KnownZero contains all the bits that are known
757/// to be zero in the expression. These are provided to potentially allow the
758/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759/// the expression. KnownOne and KnownZero always follow the invariant that
760/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761/// the bits in KnownOne and KnownZero may only be accurate for those bits set
762/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763/// and KnownOne must all be the same.
764bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765 APInt& KnownZero, APInt& KnownOne,
766 unsigned Depth) {
767 assert(V != 0 && "Null pointer of Value???");
768 assert(Depth <= 6 && "Limit Search Depth");
769 uint32_t BitWidth = DemandedMask.getBitWidth();
770 const IntegerType *VTy = cast<IntegerType>(V->getType());
771 assert(VTy->getBitWidth() == BitWidth &&
772 KnownZero.getBitWidth() == BitWidth &&
773 KnownOne.getBitWidth() == BitWidth &&
774 "Value *V, DemandedMask, KnownZero and KnownOne \
775 must have same BitWidth");
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777 // We know all of the bits for a constant!
778 KnownOne = CI->getValue() & DemandedMask;
779 KnownZero = ~KnownOne & DemandedMask;
780 return false;
781 }
782
Zhou Sheng96704452007-03-14 03:21:24 +0000783 KnownZero.clear();
784 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000785 if (!V->hasOneUse()) { // Other users may use these bits.
786 if (Depth != 0) { // Not at the root.
787 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
789 return false;
790 }
791 // If this is the root being simplified, allow it to have multiple uses,
792 // just set the DemandedMask to all bits.
793 DemandedMask = APInt::getAllOnesValue(BitWidth);
794 } else if (DemandedMask == 0) { // Not demanding any bits from V.
795 if (V != UndefValue::get(VTy))
796 return UpdateValueUsesWith(V, UndefValue::get(VTy));
797 return false;
798 } else if (Depth == 6) { // Limit search depth.
799 return false;
800 }
801
802 Instruction *I = dyn_cast<Instruction>(V);
803 if (!I) return false; // Only analyze instructions.
804
Reid Spencer8cb68342007-03-12 17:25:59 +0000805 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000808 default:
809 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000811 case Instruction::And:
812 // If either the LHS or the RHS are Zero, the result is zero.
813 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814 RHSKnownZero, RHSKnownOne, Depth+1))
815 return true;
816 assert((RHSKnownZero & RHSKnownOne) == 0 &&
817 "Bits known to be one AND zero?");
818
819 // If something is known zero on the RHS, the bits aren't demanded on the
820 // LHS.
821 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822 LHSKnownZero, LHSKnownOne, Depth+1))
823 return true;
824 assert((LHSKnownZero & LHSKnownOne) == 0 &&
825 "Bits known to be one AND zero?");
826
827 // If all of the demanded bits are known 1 on one side, return the other.
828 // These bits cannot contribute to the result of the 'and'.
829 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
830 (DemandedMask & ~LHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(0));
832 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
833 (DemandedMask & ~RHSKnownZero))
834 return UpdateValueUsesWith(I, I->getOperand(1));
835
836 // If all of the demanded bits in the inputs are known zeros, return zero.
837 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839
840 // If the RHS is a constant, see if we can simplify it.
841 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842 return UpdateValueUsesWith(I, I);
843
844 // Output known-1 bits are only known if set in both the LHS & RHS.
845 RHSKnownOne &= LHSKnownOne;
846 // Output known-0 are known to be clear if zero in either the LHS | RHS.
847 RHSKnownZero |= LHSKnownZero;
848 break;
849 case Instruction::Or:
850 // If either the LHS or the RHS are One, the result is One.
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1))
853 return true;
854 assert((RHSKnownZero & RHSKnownOne) == 0 &&
855 "Bits known to be one AND zero?");
856 // If something is known one on the RHS, the bits aren't demanded on the
857 // LHS.
858 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
859 LHSKnownZero, LHSKnownOne, Depth+1))
860 return true;
861 assert((LHSKnownZero & LHSKnownOne) == 0 &&
862 "Bits known to be one AND zero?");
863
864 // If all of the demanded bits are known zero on one side, return the other.
865 // These bits cannot contribute to the result of the 'or'.
866 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
867 (DemandedMask & ~LHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
870 (DemandedMask & ~RHSKnownOne))
871 return UpdateValueUsesWith(I, I->getOperand(1));
872
873 // If all of the potentially set bits on one side are known to be set on
874 // the other side, just use the 'other' side.
875 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
876 (DemandedMask & (~RHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
879 (DemandedMask & (~LHSKnownZero)))
880 return UpdateValueUsesWith(I, I->getOperand(1));
881
882 // If the RHS is a constant, see if we can simplify it.
883 if (ShrinkDemandedConstant(I, 1, DemandedMask))
884 return UpdateValueUsesWith(I, I);
885
886 // Output known-0 bits are only known if clear in both the LHS & RHS.
887 RHSKnownZero &= LHSKnownZero;
888 // Output known-1 are known to be set if set in either the LHS | RHS.
889 RHSKnownOne |= LHSKnownOne;
890 break;
891 case Instruction::Xor: {
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1))
894 return true;
895 assert((RHSKnownZero & RHSKnownOne) == 0 &&
896 "Bits known to be one AND zero?");
897 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
898 LHSKnownZero, LHSKnownOne, Depth+1))
899 return true;
900 assert((LHSKnownZero & LHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'xor'.
905 if ((DemandedMask & RHSKnownZero) == DemandedMask)
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & LHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(1));
909
910 // Output known-0 bits are known if clear or set in both the LHS & RHS.
911 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
912 (RHSKnownOne & LHSKnownOne);
913 // Output known-1 are known to be set if set in only one of the LHS, RHS.
914 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
915 (RHSKnownOne & LHSKnownZero);
916
917 // If all of the demanded bits are known to be zero on one side or the
918 // other, turn this into an *inclusive* or.
919 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000922 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 I->getName());
924 InsertNewInstBefore(Or, *I);
925 return UpdateValueUsesWith(I, Or);
926 }
927
928 // If all of the demanded bits on one side are known, and all of the set
929 // bits on that side are also known to be set on the other side, turn this
930 // into an AND, as we know the bits will be cleared.
931 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
933 // all known
934 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000937 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 InsertNewInstBefore(And, *I);
939 return UpdateValueUsesWith(I, And);
940 }
941 }
942
943 // If the RHS is a constant, see if we can simplify it.
944 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945 if (ShrinkDemandedConstant(I, 1, DemandedMask))
946 return UpdateValueUsesWith(I, I);
947
948 RHSKnownZero = KnownZeroOut;
949 RHSKnownOne = KnownOneOut;
950 break;
951 }
952 case Instruction::Select:
953 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954 RHSKnownZero, RHSKnownOne, Depth+1))
955 return true;
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 LHSKnownZero, LHSKnownOne, Depth+1))
958 return true;
959 assert((RHSKnownZero & RHSKnownOne) == 0 &&
960 "Bits known to be one AND zero?");
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If the operands are constants, see if we can simplify them.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask))
966 return UpdateValueUsesWith(I, I);
967 if (ShrinkDemandedConstant(I, 2, DemandedMask))
968 return UpdateValueUsesWith(I, I);
969
970 // Only known if known in both the LHS and RHS.
971 RHSKnownOne &= LHSKnownOne;
972 RHSKnownZero &= LHSKnownZero;
973 break;
974 case Instruction::Trunc: {
975 uint32_t truncBf =
976 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000977 DemandedMask.zext(truncBf);
978 RHSKnownZero.zext(truncBf);
979 RHSKnownOne.zext(truncBf);
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
981 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000982 return true;
983 DemandedMask.trunc(BitWidth);
984 RHSKnownZero.trunc(BitWidth);
985 RHSKnownOne.trunc(BitWidth);
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988 break;
989 }
990 case Instruction::BitCast:
991 if (!I->getOperand(0)->getType()->isInteger())
992 return false;
993
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
996 return true;
997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
999 break;
1000 case Instruction::ZExt: {
1001 // Compute the bits in the result that are not present in the input.
1002 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001003 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
Zhou Shengd48653a2007-03-29 04:45:55 +00001005 DemandedMask.trunc(SrcBitWidth);
1006 RHSKnownZero.trunc(SrcBitWidth);
1007 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001010 return true;
1011 DemandedMask.zext(BitWidth);
1012 RHSKnownZero.zext(BitWidth);
1013 RHSKnownOne.zext(BitWidth);
1014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1015 "Bits known to be one AND zero?");
1016 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001017 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 break;
1019 }
1020 case Instruction::SExt: {
1021 // Compute the bits in the result that are not present in the input.
1022 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001023 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001024
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001026 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
Zhou Sheng01542f32007-03-29 02:26:30 +00001028 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 // If any of the sign extended bits are demanded, we know that the sign
1030 // bit is demanded.
1031 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001032 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001033
Zhou Shengd48653a2007-03-29 04:45:55 +00001034 InputDemandedBits.trunc(SrcBitWidth);
1035 RHSKnownZero.trunc(SrcBitWidth);
1036 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001037 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 return true;
1040 InputDemandedBits.zext(BitWidth);
1041 RHSKnownZero.zext(BitWidth);
1042 RHSKnownOne.zext(BitWidth);
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1045
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1048
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001056 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 }
1059 break;
1060 }
1061 case Instruction::Add: {
1062 // Figure out what the input bits are. If the top bits of the and result
1063 // are not demanded, then the add doesn't demand them from its input
1064 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001065 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001066
1067 // If there is a constant on the RHS, there are a variety of xformations
1068 // we can do.
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isZero())
1073 break;
1074
1075 // If the top bit of the output is demanded, demand everything from the
1076 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001077 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001078
1079 // Find information about known zero/one bits in the input.
1080 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1082 return true;
1083
1084 // If the RHS of the add has bits set that can't affect the input, reduce
1085 // the constant.
1086 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087 return UpdateValueUsesWith(I, I);
1088
1089 // Avoid excess work.
1090 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1091 break;
1092
1093 // Turn it into OR if input bits are zero.
1094 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001096 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 I->getName());
1098 InsertNewInstBefore(Or, *I);
1099 return UpdateValueUsesWith(I, Or);
1100 }
1101
1102 // We can say something about the output known-zero and known-one bits,
1103 // depending on potential carries from the input constant and the
1104 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1105 // bits set and the RHS constant is 0x01001, then we know we have a known
1106 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107
1108 // To compute this, we first compute the potential carry bits. These are
1109 // the bits which may be modified. I'm not aware of a better way to do
1110 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001111 const APInt& RHSVal = RHS->getValue();
1112 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
1114 // Now that we know which bits have carries, compute the known-1/0 sets.
1115
1116 // Bits are known one if they are known zero in one operand and one in the
1117 // other, and there is no input carry.
1118 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1119 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120
1121 // Bits are known zero if they are known zero in both operands and there
1122 // is no input carry.
1123 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124 } else {
1125 // If the high-bits of this ADD are not demanded, then it does not demand
1126 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001127 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001128 // Right fill the mask of bits for this ADD to demand the most
1129 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1133 return true;
1134 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135 LHSKnownZero, LHSKnownOne, Depth+1))
1136 return true;
1137 }
1138 }
1139 break;
1140 }
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001147 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1151 return true;
1152 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153 LHSKnownZero, LHSKnownOne, Depth+1))
1154 return true;
1155 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001156 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157 // the known zeros and ones.
1158 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 break;
1160 case Instruction::Shl:
1161 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001162 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 RHSKnownZero, RHSKnownOne, Depth+1))
1166 return true;
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 RHSKnownZero <<= ShiftAmt;
1170 RHSKnownOne <<= ShiftAmt;
1171 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001172 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001173 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 }
1175 break;
1176 case Instruction::LShr:
1177 // For a logical shift right
1178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001179 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001182 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001184 RHSKnownZero, RHSKnownOne, Depth+1))
1185 return true;
1186 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1187 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001190 if (ShiftAmt) {
1191 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001193 RHSKnownZero |= HighBits; // high bits known zero.
1194 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 }
1196 break;
1197 case Instruction::AShr:
1198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
1202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001204 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 I->getOperand(0), I->getOperand(1), I->getName());
1206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207 return UpdateValueUsesWith(I, NewVal);
1208 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001209
1210 // If the sign bit is the only bit demanded by this ashr, then there is no
1211 // need to do it, the shift doesn't change the high bit.
1212 if (DemandedMask.isSignBit())
1213 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001216 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001220 // If any of the "high bits" are demanded, we should set the sign bit as
1221 // demanded.
1222 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 RHSKnownZero, RHSKnownOne, Depth+1))
1227 return true;
1228 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1229 "Bits known to be one AND zero?");
1230 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234
1235 // Handle the sign bits.
1236 APInt SignBit(APInt::getSignBit(BitWidth));
1237 // Adjust to where it is now in the mask.
1238 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1239
1240 // If the input sign bit is known to be zero, or if none of the top bits
1241 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001242 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 (HighBits & ~DemandedMask) == HighBits) {
1244 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001245 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 I->getOperand(0), SA, I->getName());
1247 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248 return UpdateValueUsesWith(I, NewVal);
1249 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250 RHSKnownOne |= HighBits;
1251 }
1252 }
1253 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue();
1257 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001258 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1259 return UpdateValueUsesWith(I, I->getOperand(0));
1260
Dan Gohman23e1df82008-05-06 00:51:48 +00001261 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001262 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1265 return true;
1266
1267 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268 LHSKnownZero |= ~LowBits;
1269 else if (LHSKnownOne[BitWidth-1])
1270 LHSKnownOne |= ~LowBits;
1271
1272 KnownZero |= LHSKnownZero & DemandedMask;
1273 KnownOne |= LHSKnownOne & DemandedMask;
1274
1275 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1276 }
1277 }
1278 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001279 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001280 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1281 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001282 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1283 KnownZero2, KnownOne2, Depth+1))
1284 return true;
1285
Dan Gohman23e8b712008-04-28 17:02:21 +00001286 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001287 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001288 KnownZero2, KnownOne2, Depth+1))
1289 return true;
1290
1291 Leaders = std::max(Leaders,
1292 KnownZero2.countLeadingOnes());
1293 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001294 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001296 case Instruction::Call:
1297 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1298 switch (II->getIntrinsicID()) {
1299 default: break;
1300 case Intrinsic::bswap: {
1301 // If the only bits demanded come from one byte of the bswap result,
1302 // just shift the input byte into position to eliminate the bswap.
1303 unsigned NLZ = DemandedMask.countLeadingZeros();
1304 unsigned NTZ = DemandedMask.countTrailingZeros();
1305
1306 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1307 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1308 // have 14 leading zeros, round to 8.
1309 NLZ &= ~7;
1310 NTZ &= ~7;
1311 // If we need exactly one byte, we can do this transformation.
1312 if (BitWidth-NLZ-NTZ == 8) {
1313 unsigned ResultBit = NTZ;
1314 unsigned InputBit = BitWidth-NTZ-8;
1315
1316 // Replace this with either a left or right shift to get the byte into
1317 // the right place.
1318 Instruction *NewVal;
1319 if (InputBit > ResultBit)
1320 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1321 ConstantInt::get(I->getType(), InputBit-ResultBit));
1322 else
1323 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1324 ConstantInt::get(I->getType(), ResultBit-InputBit));
1325 NewVal->takeName(I);
1326 InsertNewInstBefore(NewVal, *I);
1327 return UpdateValueUsesWith(I, NewVal);
1328 }
1329
1330 // TODO: Could compute known zero/one bits based on the input.
1331 break;
1332 }
1333 }
1334 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001335 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001336 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001337 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001338
1339 // If the client is only demanding bits that we know, return the known
1340 // constant.
1341 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1342 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1343 return false;
1344}
1345
Chris Lattner867b99f2006-10-05 06:55:50 +00001346
1347/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1348/// 64 or fewer elements. DemandedElts contains the set of elements that are
1349/// actually used by the caller. This method analyzes which elements of the
1350/// operand are undef and returns that information in UndefElts.
1351///
1352/// If the information about demanded elements can be used to simplify the
1353/// operation, the operation is simplified, then the resultant value is
1354/// returned. This returns null if no change was made.
1355Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1356 uint64_t &UndefElts,
1357 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001358 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001359 assert(VWidth <= 64 && "Vector too wide to analyze!");
1360 uint64_t EltMask = ~0ULL >> (64-VWidth);
1361 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1362 "Invalid DemandedElts!");
1363
1364 if (isa<UndefValue>(V)) {
1365 // If the entire vector is undefined, just return this info.
1366 UndefElts = EltMask;
1367 return 0;
1368 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369 UndefElts = EltMask;
1370 return UndefValue::get(V->getType());
1371 }
1372
1373 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001374 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001376 Constant *Undef = UndefValue::get(EltTy);
1377
1378 std::vector<Constant*> Elts;
1379 for (unsigned i = 0; i != VWidth; ++i)
1380 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1384 Elts.push_back(Undef);
1385 UndefElts |= (1ULL << i);
1386 } else { // Otherwise, defined.
1387 Elts.push_back(CP->getOperand(i));
1388 }
1389
1390 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001391 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001392 return NewCP != CP ? NewCP : 0;
1393 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001394 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001395 // set to undef.
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
1406 if (!V->hasOneUse()) { // Other users may use these bits.
1407 if (Depth != 0) { // Not at the root.
1408 // TODO: Just compute the UndefElts information recursively.
1409 return false;
1410 }
1411 return false;
1412 } else if (Depth == 10) { // Limit search depth.
1413 return false;
1414 }
1415
1416 Instruction *I = dyn_cast<Instruction>(V);
1417 if (!I) return false; // Only analyze instructions.
1418
1419 bool MadeChange = false;
1420 uint64_t UndefElts2;
1421 Value *TmpV;
1422 switch (I->getOpcode()) {
1423 default: break;
1424
1425 case Instruction::InsertElement: {
1426 // If this is a variable index, we don't know which element it overwrites.
1427 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001428 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001429 if (Idx == 0) {
1430 // Note that we can't propagate undef elt info, because we don't know
1431 // which elt is getting updated.
1432 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1433 UndefElts2, Depth+1);
1434 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1435 break;
1436 }
1437
1438 // If this is inserting an element that isn't demanded, remove this
1439 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001440 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1442 return AddSoonDeadInstToWorklist(*I, 0);
1443
1444 // Otherwise, the element inserted overwrites whatever was there, so the
1445 // input demanded set is simpler than the output set.
1446 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1447 DemandedElts & ~(1ULL << IdxNo),
1448 UndefElts, Depth+1);
1449 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450
1451 // The inserted element is defined.
1452 UndefElts |= 1ULL << IdxNo;
1453 break;
1454 }
Chris Lattner69878332007-04-14 22:29:23 +00001455 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001456 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001457 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1458 if (!VTy) break;
1459 unsigned InVWidth = VTy->getNumElements();
1460 uint64_t InputDemandedElts = 0;
1461 unsigned Ratio;
1462
1463 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001464 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001465 // elements as are demanded of us.
1466 Ratio = 1;
1467 InputDemandedElts = DemandedElts;
1468 } else if (VWidth > InVWidth) {
1469 // Untested so far.
1470 break;
1471
1472 // If there are more elements in the result than there are in the source,
1473 // then an input element is live if any of the corresponding output
1474 // elements are live.
1475 Ratio = VWidth/InVWidth;
1476 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1477 if (DemandedElts & (1ULL << OutIdx))
1478 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1479 }
1480 } else {
1481 // Untested so far.
1482 break;
1483
1484 // If there are more elements in the source than there are in the result,
1485 // then an input element is live if the corresponding output element is
1486 // live.
1487 Ratio = InVWidth/VWidth;
1488 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1489 if (DemandedElts & (1ULL << InIdx/Ratio))
1490 InputDemandedElts |= 1ULL << InIdx;
1491 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001492
Chris Lattner69878332007-04-14 22:29:23 +00001493 // div/rem demand all inputs, because they don't want divide by zero.
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1495 UndefElts2, Depth+1);
1496 if (TmpV) {
1497 I->setOperand(0, TmpV);
1498 MadeChange = true;
1499 }
1500
1501 UndefElts = UndefElts2;
1502 if (VWidth > InVWidth) {
1503 assert(0 && "Unimp");
1504 // If there are more elements in the result than there are in the source,
1505 // then an output element is undef if the corresponding input element is
1506 // undef.
1507 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1508 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1509 UndefElts |= 1ULL << OutIdx;
1510 } else if (VWidth < InVWidth) {
1511 assert(0 && "Unimp");
1512 // If there are more elements in the source than there are in the result,
1513 // then a result element is undef if all of the corresponding input
1514 // elements are undef.
1515 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1516 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1517 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1518 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1519 }
1520 break;
1521 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 case Instruction::And:
1523 case Instruction::Or:
1524 case Instruction::Xor:
1525 case Instruction::Add:
1526 case Instruction::Sub:
1527 case Instruction::Mul:
1528 // div/rem demand all inputs, because they don't want divide by zero.
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530 UndefElts, Depth+1);
1531 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1533 UndefElts2, Depth+1);
1534 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1535
1536 // Output elements are undefined if both are undefined. Consider things
1537 // like undef&0. The result is known zero, not undef.
1538 UndefElts &= UndefElts2;
1539 break;
1540
1541 case Instruction::Call: {
1542 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1543 if (!II) break;
1544 switch (II->getIntrinsicID()) {
1545 default: break;
1546
1547 // Binary vector operations that work column-wise. A dest element is a
1548 // function of the corresponding input elements from the two inputs.
1549 case Intrinsic::x86_sse_sub_ss:
1550 case Intrinsic::x86_sse_mul_ss:
1551 case Intrinsic::x86_sse_min_ss:
1552 case Intrinsic::x86_sse_max_ss:
1553 case Intrinsic::x86_sse2_sub_sd:
1554 case Intrinsic::x86_sse2_mul_sd:
1555 case Intrinsic::x86_sse2_min_sd:
1556 case Intrinsic::x86_sse2_max_sd:
1557 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1558 UndefElts, Depth+1);
1559 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1560 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1561 UndefElts2, Depth+1);
1562 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1563
1564 // If only the low elt is demanded and this is a scalarizable intrinsic,
1565 // scalarize it now.
1566 if (DemandedElts == 1) {
1567 switch (II->getIntrinsicID()) {
1568 default: break;
1569 case Intrinsic::x86_sse_sub_ss:
1570 case Intrinsic::x86_sse_mul_ss:
1571 case Intrinsic::x86_sse2_sub_sd:
1572 case Intrinsic::x86_sse2_mul_sd:
1573 // TODO: Lower MIN/MAX/ABS/etc
1574 Value *LHS = II->getOperand(1);
1575 Value *RHS = II->getOperand(2);
1576 // Extract the element as scalars.
1577 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1578 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1579
1580 switch (II->getIntrinsicID()) {
1581 default: assert(0 && "Case stmts out of sync!");
1582 case Intrinsic::x86_sse_sub_ss:
1583 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001584 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001585 II->getName()), *II);
1586 break;
1587 case Intrinsic::x86_sse_mul_ss:
1588 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001589 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001590 II->getName()), *II);
1591 break;
1592 }
1593
1594 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001595 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1596 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 InsertNewInstBefore(New, *II);
1598 AddSoonDeadInstToWorklist(*II, 0);
1599 return New;
1600 }
1601 }
1602
1603 // Output elements are undefined if both are undefined. Consider things
1604 // like undef&0. The result is known zero, not undef.
1605 UndefElts &= UndefElts2;
1606 break;
1607 }
1608 break;
1609 }
1610 }
1611 return MadeChange ? I : 0;
1612}
1613
Dan Gohman45b4e482008-05-19 22:14:15 +00001614
Chris Lattner564a7272003-08-13 19:01:45 +00001615/// AssociativeOpt - Perform an optimization on an associative operator. This
1616/// function is designed to check a chain of associative operators for a
1617/// potential to apply a certain optimization. Since the optimization may be
1618/// applicable if the expression was reassociated, this checks the chain, then
1619/// reassociates the expression as necessary to expose the optimization
1620/// opportunity. This makes use of a special Functor, which must define
1621/// 'shouldApply' and 'apply' methods.
1622///
1623template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001624static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001625 unsigned Opcode = Root.getOpcode();
1626 Value *LHS = Root.getOperand(0);
1627
1628 // Quick check, see if the immediate LHS matches...
1629 if (F.shouldApply(LHS))
1630 return F.apply(Root);
1631
1632 // Otherwise, if the LHS is not of the same opcode as the root, return.
1633 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001634 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001635 // Should we apply this transform to the RHS?
1636 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1637
1638 // If not to the RHS, check to see if we should apply to the LHS...
1639 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1640 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1641 ShouldApply = true;
1642 }
1643
1644 // If the functor wants to apply the optimization to the RHS of LHSI,
1645 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1646 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001647 // Now all of the instructions are in the current basic block, go ahead
1648 // and perform the reassociation.
1649 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1650
1651 // First move the selected RHS to the LHS of the root...
1652 Root.setOperand(0, LHSI->getOperand(1));
1653
1654 // Make what used to be the LHS of the root be the user of the root...
1655 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001656 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001657 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1658 return 0;
1659 }
Chris Lattner65725312004-04-16 18:08:07 +00001660 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001661 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001662 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001663 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001664 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001665
1666 // Now propagate the ExtraOperand down the chain of instructions until we
1667 // get to LHSI.
1668 while (TmpLHSI != LHSI) {
1669 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001670 // Move the instruction to immediately before the chain we are
1671 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001672 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001673 ARI = NextLHSI;
1674
Chris Lattner564a7272003-08-13 19:01:45 +00001675 Value *NextOp = NextLHSI->getOperand(1);
1676 NextLHSI->setOperand(1, ExtraOperand);
1677 TmpLHSI = NextLHSI;
1678 ExtraOperand = NextOp;
1679 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001680
Chris Lattner564a7272003-08-13 19:01:45 +00001681 // Now that the instructions are reassociated, have the functor perform
1682 // the transformation...
1683 return F.apply(Root);
1684 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001685
Chris Lattner564a7272003-08-13 19:01:45 +00001686 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1687 }
1688 return 0;
1689}
1690
Dan Gohman844731a2008-05-13 00:00:25 +00001691namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001692
Nick Lewycky02d639f2008-05-23 04:34:58 +00001693// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001694struct AddRHS {
1695 Value *RHS;
1696 AddRHS(Value *rhs) : RHS(rhs) {}
1697 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1698 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001699 return BinaryOperator::CreateShl(Add.getOperand(0),
1700 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001701 }
1702};
1703
1704// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1705// iff C1&C2 == 0
1706struct AddMaskingAnd {
1707 Constant *C2;
1708 AddMaskingAnd(Constant *c) : C2(c) {}
1709 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001710 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001711 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001712 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001713 }
1714 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001715 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001716 }
1717};
1718
Dan Gohman844731a2008-05-13 00:00:25 +00001719}
1720
Chris Lattner6e7ba452005-01-01 16:22:27 +00001721static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001722 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001723 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001724 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001725 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001726
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001727 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001728 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001729 }
1730
Chris Lattner2eefe512004-04-09 19:05:30 +00001731 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001732 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1733 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001734
Chris Lattner2eefe512004-04-09 19:05:30 +00001735 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1736 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001737 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1738 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001739 }
1740
1741 Value *Op0 = SO, *Op1 = ConstOperand;
1742 if (!ConstIsRHS)
1743 std::swap(Op0, Op1);
1744 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001745 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001746 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001747 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001748 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001749 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001750 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001751 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001752 abort();
1753 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001754 return IC->InsertNewInstBefore(New, I);
1755}
1756
1757// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1758// constant as the other operand, try to fold the binary operator into the
1759// select arguments. This also works for Cast instructions, which obviously do
1760// not have a second operand.
1761static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1762 InstCombiner *IC) {
1763 // Don't modify shared select instructions
1764 if (!SI->hasOneUse()) return 0;
1765 Value *TV = SI->getOperand(1);
1766 Value *FV = SI->getOperand(2);
1767
1768 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001769 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001770 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001771
Chris Lattner6e7ba452005-01-01 16:22:27 +00001772 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1773 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1774
Gabor Greif051a9502008-04-06 20:25:17 +00001775 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1776 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001777 }
1778 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001779}
1780
Chris Lattner4e998b22004-09-29 05:07:12 +00001781
1782/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1783/// node as operand #0, see if we can fold the instruction into the PHI (which
1784/// is only possible if all operands to the PHI are constants).
1785Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1786 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001787 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001788 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001789
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001790 // Check to see if all of the operands of the PHI are constants. If there is
1791 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001792 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001793 BasicBlock *NonConstBB = 0;
1794 for (unsigned i = 0; i != NumPHIValues; ++i)
1795 if (!isa<Constant>(PN->getIncomingValue(i))) {
1796 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001797 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001798 NonConstBB = PN->getIncomingBlock(i);
1799
1800 // If the incoming non-constant value is in I's block, we have an infinite
1801 // loop.
1802 if (NonConstBB == I.getParent())
1803 return 0;
1804 }
1805
1806 // If there is exactly one non-constant value, we can insert a copy of the
1807 // operation in that block. However, if this is a critical edge, we would be
1808 // inserting the computation one some other paths (e.g. inside a loop). Only
1809 // do this if the pred block is unconditionally branching into the phi block.
1810 if (NonConstBB) {
1811 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1812 if (!BI || !BI->isUnconditional()) return 0;
1813 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001814
1815 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001816 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001817 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001818 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001819 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001820
1821 // Next, add all of the operands to the PHI.
1822 if (I.getNumOperands() == 2) {
1823 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001824 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001825 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001827 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1828 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1829 else
1830 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001831 } else {
1832 assert(PN->getIncomingBlock(i) == NonConstBB);
1833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001834 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001835 PN->getIncomingValue(i), C, "phitmp",
1836 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001837 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001838 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001839 CI->getPredicate(),
1840 PN->getIncomingValue(i), C, "phitmp",
1841 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001842 else
1843 assert(0 && "Unknown binop!");
1844
Chris Lattnerdbab3862007-03-02 21:28:56 +00001845 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001846 }
1847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001848 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001849 } else {
1850 CastInst *CI = cast<CastInst>(&I);
1851 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001852 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001853 Value *InV;
1854 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001855 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001856 } else {
1857 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001858 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001859 I.getType(), "phitmp",
1860 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001861 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001862 }
1863 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001864 }
1865 }
1866 return ReplaceInstUsesWith(I, NewPN);
1867}
1868
Chris Lattner2454a2e2008-01-29 06:52:45 +00001869
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001870/// WillNotOverflowSignedAdd - Return true if we can prove that:
1871/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1872/// This basically requires proving that the add in the original type would not
1873/// overflow to change the sign bit or have a carry out.
1874bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1875 // There are different heuristics we can use for this. Here are some simple
1876 // ones.
1877
1878 // Add has the property that adding any two 2's complement numbers can only
1879 // have one carry bit which can change a sign. As such, if LHS and RHS each
1880 // have at least two sign bits, we know that the addition of the two values will
1881 // sign extend fine.
1882 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1883 return true;
1884
1885
1886 // If one of the operands only has one non-zero bit, and if the other operand
1887 // has a known-zero bit in a more significant place than it (not including the
1888 // sign bit) the ripple may go up to and fill the zero, but won't change the
1889 // sign. For example, (X & ~4) + 1.
1890
1891 // TODO: Implement.
1892
1893 return false;
1894}
1895
Chris Lattner2454a2e2008-01-29 06:52:45 +00001896
Chris Lattner7e708292002-06-25 16:13:24 +00001897Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001898 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001899 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001900
Chris Lattner66331a42004-04-10 22:01:55 +00001901 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001902 // X + undef -> undef
1903 if (isa<UndefValue>(RHS))
1904 return ReplaceInstUsesWith(I, RHS);
1905
Chris Lattner66331a42004-04-10 22:01:55 +00001906 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001907 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001908 if (RHSC->isNullValue())
1909 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001910 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001911 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1912 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001913 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001914 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001915
Chris Lattner66331a42004-04-10 22:01:55 +00001916 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001917 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001918 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001919 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001920 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001921 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001922
1923 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1924 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001925 if (!isa<VectorType>(I.getType())) {
1926 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1927 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1928 KnownZero, KnownOne))
1929 return &I;
1930 }
Chris Lattner66331a42004-04-10 22:01:55 +00001931 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001932
1933 if (isa<PHINode>(LHS))
1934 if (Instruction *NV = FoldOpIntoPhi(I))
1935 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001936
Chris Lattner4f637d42006-01-06 17:59:59 +00001937 ConstantInt *XorRHS = 0;
1938 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001939 if (isa<ConstantInt>(RHSC) &&
1940 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001941 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001942 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001943
Zhou Sheng4351c642007-04-02 08:20:41 +00001944 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001945 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1946 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001947 do {
1948 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001949 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1950 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001951 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1952 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001953 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001954 if (!MaskedValueIsZero(XorLHS,
1955 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001956 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001957 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001958 }
1959 }
1960 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001961 C0080Val = APIntOps::lshr(C0080Val, Size);
1962 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1963 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001964
Reid Spencer35c38852007-03-28 01:36:16 +00001965 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001966 // with funny bit widths then this switch statement should be removed. It
1967 // is just here to get the size of the "middle" type back up to something
1968 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001969 const Type *MiddleType = 0;
1970 switch (Size) {
1971 default: break;
1972 case 32: MiddleType = Type::Int32Ty; break;
1973 case 16: MiddleType = Type::Int16Ty; break;
1974 case 8: MiddleType = Type::Int8Ty; break;
1975 }
1976 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001977 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001978 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001979 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001980 }
1981 }
Chris Lattner66331a42004-04-10 22:01:55 +00001982 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001983
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001984 if (I.getType() == Type::Int1Ty)
1985 return BinaryOperator::CreateXor(LHS, RHS);
1986
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001987 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001988 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001989 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001990
1991 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1992 if (RHSI->getOpcode() == Instruction::Sub)
1993 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1994 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1995 }
1996 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1997 if (LHSI->getOpcode() == Instruction::Sub)
1998 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1999 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2000 }
Robert Bocchino71698282004-07-27 21:02:21 +00002001 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002002
Chris Lattner5c4afb92002-05-08 22:46:53 +00002003 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002004 // -A + -B --> -(A + B)
2005 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002006 if (LHS->getType()->isIntOrIntVector()) {
2007 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002008 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002009 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002010 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002011 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002012 }
2013
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002014 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002015 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002016
2017 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002018 if (!isa<Constant>(RHS))
2019 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002020 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002021
Misha Brukmanfd939082005-04-21 23:48:37 +00002022
Chris Lattner50af16a2004-11-13 19:50:12 +00002023 ConstantInt *C2;
2024 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2025 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002026 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002027
2028 // X*C1 + X*C2 --> X * (C1+C2)
2029 ConstantInt *C1;
2030 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002031 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002032 }
2033
2034 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002035 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002036 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002037
Chris Lattnere617c9e2007-01-05 02:17:46 +00002038 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002039 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2040 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002041
Chris Lattnerad3448c2003-02-18 19:57:07 +00002042
Chris Lattner564a7272003-08-13 19:01:45 +00002043 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002044 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002045 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2046 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002047
2048 // A+B --> A|B iff A and B have no bits set in common.
2049 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2050 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2051 APInt LHSKnownOne(IT->getBitWidth(), 0);
2052 APInt LHSKnownZero(IT->getBitWidth(), 0);
2053 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2054 if (LHSKnownZero != 0) {
2055 APInt RHSKnownOne(IT->getBitWidth(), 0);
2056 APInt RHSKnownZero(IT->getBitWidth(), 0);
2057 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2058
2059 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002060 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002061 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002062 }
2063 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002064
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002065 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002066 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002067 Value *W, *X, *Y, *Z;
2068 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2069 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2070 if (W != Y) {
2071 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002072 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002073 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002074 std::swap(W, X);
2075 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002076 std::swap(Y, Z);
2077 std::swap(W, X);
2078 }
2079 }
2080
2081 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002082 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002083 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002084 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002085 }
2086 }
2087 }
2088
Chris Lattner6b032052003-10-02 15:11:26 +00002089 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002090 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002091 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002092 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002093
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002094 // (X & FF00) + xx00 -> (X+xx00) & FF00
2095 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002096 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002097 if (Anded == CRHS) {
2098 // See if all bits from the first bit set in the Add RHS up are included
2099 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002100 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002101
2102 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002103 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002104
2105 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002106 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002107
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002108 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2109 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002110 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002111 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002112 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002113 }
2114 }
2115 }
2116
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002117 // Try to fold constant add into select arguments.
2118 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002119 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002120 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002121 }
2122
Reid Spencer1628cec2006-10-26 06:15:43 +00002123 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002124 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002125 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002126 CastInst *CI = dyn_cast<CastInst>(LHS);
2127 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002128 if (!CI) {
2129 CI = dyn_cast<CastInst>(RHS);
2130 Other = LHS;
2131 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002132 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002133 (CI->getType()->getPrimitiveSizeInBits() ==
2134 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002135 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002136 unsigned AS =
2137 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002138 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2139 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002140 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002141 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002142 }
2143 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002144
Chris Lattner42790482007-12-20 01:56:58 +00002145 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002146 {
2147 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2148 Value *Other = RHS;
2149 if (!SI) {
2150 SI = dyn_cast<SelectInst>(RHS);
2151 Other = LHS;
2152 }
Chris Lattner42790482007-12-20 01:56:58 +00002153 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002154 Value *TV = SI->getTrueValue();
2155 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002156 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002157
2158 // Can we fold the add into the argument of the select?
2159 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002160 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2161 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002162 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002163 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2164 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002165 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002166 }
2167 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002168
2169 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2170 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2171 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2172 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002173
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002174 // Check for (add (sext x), y), see if we can merge this into an
2175 // integer add followed by a sext.
2176 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2177 // (add (sext x), cst) --> (sext (add x, cst'))
2178 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2179 Constant *CI =
2180 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2181 if (LHSConv->hasOneUse() &&
2182 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2183 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2184 // Insert the new, smaller add.
2185 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2186 CI, "addconv");
2187 InsertNewInstBefore(NewAdd, I);
2188 return new SExtInst(NewAdd, I.getType());
2189 }
2190 }
2191
2192 // (add (sext x), (sext y)) --> (sext (add int x, y))
2193 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2194 // Only do this if x/y have the same type, if at last one of them has a
2195 // single use (so we don't increase the number of sexts), and if the
2196 // integer add will not overflow.
2197 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2198 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2199 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2200 RHSConv->getOperand(0))) {
2201 // Insert the new integer add.
2202 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2203 RHSConv->getOperand(0),
2204 "addconv");
2205 InsertNewInstBefore(NewAdd, I);
2206 return new SExtInst(NewAdd, I.getType());
2207 }
2208 }
2209 }
2210
2211 // Check for (add double (sitofp x), y), see if we can merge this into an
2212 // integer add followed by a promotion.
2213 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2214 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2215 // ... if the constant fits in the integer value. This is useful for things
2216 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2217 // requires a constant pool load, and generally allows the add to be better
2218 // instcombined.
2219 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2220 Constant *CI =
2221 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2222 if (LHSConv->hasOneUse() &&
2223 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2224 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2225 // Insert the new integer add.
2226 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2227 CI, "addconv");
2228 InsertNewInstBefore(NewAdd, I);
2229 return new SIToFPInst(NewAdd, I.getType());
2230 }
2231 }
2232
2233 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2234 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2235 // Only do this if x/y have the same type, if at last one of them has a
2236 // single use (so we don't increase the number of int->fp conversions),
2237 // and if the integer add will not overflow.
2238 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2239 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2240 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2241 RHSConv->getOperand(0))) {
2242 // Insert the new integer add.
2243 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2244 RHSConv->getOperand(0),
2245 "addconv");
2246 InsertNewInstBefore(NewAdd, I);
2247 return new SIToFPInst(NewAdd, I.getType());
2248 }
2249 }
2250 }
2251
Chris Lattner7e708292002-06-25 16:13:24 +00002252 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002253}
2254
Chris Lattner7e708292002-06-25 16:13:24 +00002255Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002257
Chris Lattnerd137ab42008-07-17 06:07:20 +00002258 if (Op0 == Op1 && // sub X, X -> 0
2259 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002261
Chris Lattner233f7dc2002-08-12 21:17:25 +00002262 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002263 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002265
Chris Lattnere87597f2004-10-16 18:11:37 +00002266 if (isa<UndefValue>(Op0))
2267 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2268 if (isa<UndefValue>(Op1))
2269 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2270
Chris Lattnerd65460f2003-11-05 01:06:05 +00002271 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2272 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002273 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002274 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002275
Chris Lattnerd65460f2003-11-05 01:06:05 +00002276 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002277 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002278 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002279 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002280
Chris Lattner76b7a062007-01-15 07:02:54 +00002281 // -(X >>u 31) -> (X >>s 31)
2282 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002283 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002284 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002285 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002286 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002287 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002288 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002289 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002290 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002291 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002292 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002293 }
2294 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002295 }
2296 else if (SI->getOpcode() == Instruction::AShr) {
2297 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2298 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002299 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002300 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002301 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002302 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002303 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002304 }
2305 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002306 }
2307 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002308 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002309
2310 // Try to fold constant sub into select arguments.
2311 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002313 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002314
2315 if (isa<PHINode>(Op0))
2316 if (Instruction *NV = FoldOpIntoPhi(I))
2317 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002318 }
2319
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002320 if (I.getType() == Type::Int1Ty)
2321 return BinaryOperator::CreateXor(Op0, Op1);
2322
Chris Lattner43d84d62005-04-07 16:15:25 +00002323 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2324 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002325 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002326 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002327 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002328 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002329 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002330 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2331 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2332 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002333 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002334 Op1I->getOperand(0));
2335 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002336 }
2337
Chris Lattnerfd059242003-10-15 16:48:29 +00002338 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002339 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2340 // is not used by anyone else...
2341 //
Chris Lattner0517e722004-02-02 20:09:56 +00002342 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002343 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002344 // Swap the two operands of the subexpr...
2345 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2346 Op1I->setOperand(0, IIOp1);
2347 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002348
Chris Lattnera2881962003-02-18 19:28:33 +00002349 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002350 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002351 }
2352
2353 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2354 //
2355 if (Op1I->getOpcode() == Instruction::And &&
2356 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2357 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2358
Chris Lattnerf523d062004-06-09 05:08:07 +00002359 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002360 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2361 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002362 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002363
Reid Spencerac5209e2006-10-16 23:08:08 +00002364 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002365 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002366 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002367 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002368 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002369 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002370 ConstantExpr::getNeg(DivRHS));
2371
Chris Lattnerad3448c2003-02-18 19:57:07 +00002372 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002373 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002374 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002375 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002376 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002377 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002378
2379 // X - ((X / Y) * Y) --> X % Y
2380 if (Op1I->getOpcode() == Instruction::Mul)
2381 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2382 if (Op0 == I->getOperand(0) &&
2383 Op1I->getOperand(1) == I->getOperand(1)) {
2384 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002385 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002386 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002387 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002388 }
Chris Lattner40371712002-05-09 01:29:19 +00002389 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002390 }
Chris Lattnera2881962003-02-18 19:28:33 +00002391
Chris Lattner9919e3d2006-12-02 00:13:08 +00002392 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002393 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002394 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002395 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2396 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2397 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2398 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002399 } else if (Op0I->getOpcode() == Instruction::Sub) {
2400 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002401 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002402 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002403 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002404
Chris Lattner50af16a2004-11-13 19:50:12 +00002405 ConstantInt *C1;
2406 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002407 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002408 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002409
Chris Lattner50af16a2004-11-13 19:50:12 +00002410 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2411 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002412 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002413 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002414 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002415}
2416
Chris Lattnera0141b92007-07-15 20:42:37 +00002417/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2418/// comparison only checks the sign bit. If it only checks the sign bit, set
2419/// TrueIfSigned if the result of the comparison is true when the input value is
2420/// signed.
2421static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2422 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002423 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002424 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2425 TrueIfSigned = true;
2426 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002427 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2428 TrueIfSigned = true;
2429 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002430 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2431 TrueIfSigned = false;
2432 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002433 case ICmpInst::ICMP_UGT:
2434 // True if LHS u> RHS and RHS == high-bit-mask - 1
2435 TrueIfSigned = true;
2436 return RHS->getValue() ==
2437 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2438 case ICmpInst::ICMP_UGE:
2439 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2440 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002441 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002442 default:
2443 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002444 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002445}
2446
Chris Lattner7e708292002-06-25 16:13:24 +00002447Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002448 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002449 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002450
Chris Lattnere87597f2004-10-16 18:11:37 +00002451 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2452 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2453
Chris Lattner233f7dc2002-08-12 21:17:25 +00002454 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002455 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2456 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002457
2458 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002459 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002460 if (SI->getOpcode() == Instruction::Shl)
2461 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002463 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002464
Zhou Sheng843f07672007-04-19 05:39:12 +00002465 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002466 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2467 if (CI->equalsInt(1)) // X * 1 == X
2468 return ReplaceInstUsesWith(I, Op0);
2469 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002470 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002471
Zhou Sheng97b52c22007-03-29 01:57:21 +00002472 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002473 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002474 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002475 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002476 }
Robert Bocchino71698282004-07-27 21:02:21 +00002477 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002478 if (Op1F->isNullValue())
2479 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002480
Chris Lattnera2881962003-02-18 19:28:33 +00002481 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2482 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002483 // We need a better interface for long double here.
2484 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2485 if (Op1F->isExactlyValue(1.0))
2486 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002487 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002488
2489 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2490 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002491 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002492 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002493 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002494 Op1, "tmp");
2495 InsertNewInstBefore(Add, I);
2496 Value *C1C2 = ConstantExpr::getMul(Op1,
2497 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002498 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002499
2500 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002501
2502 // Try to fold constant mul into select arguments.
2503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002504 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002505 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002506
2507 if (isa<PHINode>(Op0))
2508 if (Instruction *NV = FoldOpIntoPhi(I))
2509 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002510 }
2511
Chris Lattnera4f445b2003-03-10 23:23:04 +00002512 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2513 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002515
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002516 if (I.getType() == Type::Int1Ty)
2517 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2518
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002519 // If one of the operands of the multiply is a cast from a boolean value, then
2520 // we know the bool is either zero or one, so this is a 'masking' multiply.
2521 // See if we can simplify things based on how the boolean was originally
2522 // formed.
2523 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002524 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002525 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002526 BoolCast = CI;
2527 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002528 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002529 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002530 BoolCast = CI;
2531 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002532 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002533 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2534 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002535 bool TIS = false;
2536
Reid Spencere4d87aa2006-12-23 06:05:41 +00002537 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002538 // multiply into a shift/and combination.
2539 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002540 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2541 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002542 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002543 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002544 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002545 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002546 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002547 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002548 BoolCast->getOperand(0)->getName()+
2549 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002550
2551 // If the multiply type is not the same as the source type, sign extend
2552 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002553 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002554 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2555 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002556 Instruction::CastOps opcode =
2557 (SrcBits == DstBits ? Instruction::BitCast :
2558 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2559 V = InsertCastBefore(opcode, V, I.getType(), I);
2560 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002561
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002562 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002563 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002564 }
2565 }
2566 }
2567
Chris Lattner7e708292002-06-25 16:13:24 +00002568 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002569}
2570
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002571/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2572/// instruction.
2573bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2574 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2575
2576 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2577 int NonNullOperand = -1;
2578 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2579 if (ST->isNullValue())
2580 NonNullOperand = 2;
2581 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2582 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2583 if (ST->isNullValue())
2584 NonNullOperand = 1;
2585
2586 if (NonNullOperand == -1)
2587 return false;
2588
2589 Value *SelectCond = SI->getOperand(0);
2590
2591 // Change the div/rem to use 'Y' instead of the select.
2592 I.setOperand(1, SI->getOperand(NonNullOperand));
2593
2594 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2595 // problem. However, the select, or the condition of the select may have
2596 // multiple uses. Based on our knowledge that the operand must be non-zero,
2597 // propagate the known value for the select into other uses of it, and
2598 // propagate a known value of the condition into its other users.
2599
2600 // If the select and condition only have a single use, don't bother with this,
2601 // early exit.
2602 if (SI->use_empty() && SelectCond->hasOneUse())
2603 return true;
2604
2605 // Scan the current block backward, looking for other uses of SI.
2606 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2607
2608 while (BBI != BBFront) {
2609 --BBI;
2610 // If we found a call to a function, we can't assume it will return, so
2611 // information from below it cannot be propagated above it.
2612 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2613 break;
2614
2615 // Replace uses of the select or its condition with the known values.
2616 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2617 I != E; ++I) {
2618 if (*I == SI) {
2619 *I = SI->getOperand(NonNullOperand);
2620 AddToWorkList(BBI);
2621 } else if (*I == SelectCond) {
2622 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2623 ConstantInt::getFalse();
2624 AddToWorkList(BBI);
2625 }
2626 }
2627
2628 // If we past the instruction, quit looking for it.
2629 if (&*BBI == SI)
2630 SI = 0;
2631 if (&*BBI == SelectCond)
2632 SelectCond = 0;
2633
2634 // If we ran out of things to eliminate, break out of the loop.
2635 if (SelectCond == 0 && SI == 0)
2636 break;
2637
2638 }
2639 return true;
2640}
2641
2642
Reid Spencer1628cec2006-10-26 06:15:43 +00002643/// This function implements the transforms on div instructions that work
2644/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2645/// used by the visitors to those instructions.
2646/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002647Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002649
Chris Lattner50b2ca42008-02-19 06:12:18 +00002650 // undef / X -> 0 for integer.
2651 // undef / X -> undef for FP (the undef could be a snan).
2652 if (isa<UndefValue>(Op0)) {
2653 if (Op0->getType()->isFPOrFPVector())
2654 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002656 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002657
2658 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002659 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002660 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002661
Reid Spencer1628cec2006-10-26 06:15:43 +00002662 return 0;
2663}
Misha Brukmanfd939082005-04-21 23:48:37 +00002664
Reid Spencer1628cec2006-10-26 06:15:43 +00002665/// This function implements the transforms common to both integer division
2666/// instructions (udiv and sdiv). It is called by the visitors to those integer
2667/// division instructions.
2668/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002669Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2671
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002672 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002673 if (Op0 == Op1) {
2674 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2675 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2676 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2677 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2678 }
2679
2680 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2681 return ReplaceInstUsesWith(I, CI);
2682 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002683
Reid Spencer1628cec2006-10-26 06:15:43 +00002684 if (Instruction *Common = commonDivTransforms(I))
2685 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002686
2687 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2688 // This does not apply for fdiv.
2689 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2690 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002691
2692 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2693 // div X, 1 == X
2694 if (RHS->equalsInt(1))
2695 return ReplaceInstUsesWith(I, Op0);
2696
2697 // (X / C1) / C2 -> X / (C1*C2)
2698 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2699 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2700 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002701 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2702 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2703 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002704 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002705 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002706 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002707
Reid Spencerbca0e382007-03-23 20:05:17 +00002708 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002709 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2710 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2711 return R;
2712 if (isa<PHINode>(Op0))
2713 if (Instruction *NV = FoldOpIntoPhi(I))
2714 return NV;
2715 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002716 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002717
Chris Lattnera2881962003-02-18 19:28:33 +00002718 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002719 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002720 if (LHS->equalsInt(0))
2721 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2722
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002723 // It can't be division by zero, hence it must be division by one.
2724 if (I.getType() == Type::Int1Ty)
2725 return ReplaceInstUsesWith(I, Op0);
2726
Reid Spencer1628cec2006-10-26 06:15:43 +00002727 return 0;
2728}
2729
2730Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2731 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2732
2733 // Handle the integer div common cases
2734 if (Instruction *Common = commonIDivTransforms(I))
2735 return Common;
2736
2737 // X udiv C^2 -> X >> C
2738 // Check to see if this is an unsigned division with an exact power of 2,
2739 // if so, convert to a right shift.
2740 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002741 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002743 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002744 }
2745
2746 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002747 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002748 if (RHSI->getOpcode() == Instruction::Shl &&
2749 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002750 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002751 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002752 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002753 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002754 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002755 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002756 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002757 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002758 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002759 }
2760 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002761 }
2762
Reid Spencer1628cec2006-10-26 06:15:43 +00002763 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2764 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002765 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002766 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002767 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002768 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002769 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002770 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002771 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002772 // Construct the "on true" case of the select
2773 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002774 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002775 Op0, TC, SI->getName()+".t");
2776 TSI = InsertNewInstBefore(TSI, I);
2777
2778 // Construct the "on false" case of the select
2779 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002780 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002781 Op0, FC, SI->getName()+".f");
2782 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002783
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002784 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002785 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002786 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002787 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002788 return 0;
2789}
2790
Reid Spencer1628cec2006-10-26 06:15:43 +00002791Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2793
2794 // Handle the integer div common cases
2795 if (Instruction *Common = commonIDivTransforms(I))
2796 return Common;
2797
2798 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2799 // sdiv X, -1 == -X
2800 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002802
2803 // -X/C -> X/-C
2804 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002805 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002806 }
2807
2808 // If the sign bits of both operands are zero (i.e. we can prove they are
2809 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002810 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002811 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002812 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002813 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002814 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002815 }
2816 }
2817
2818 return 0;
2819}
2820
2821Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2822 return commonDivTransforms(I);
2823}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002824
Reid Spencer0a783f72006-11-02 01:53:59 +00002825/// This function implements the transforms on rem instructions that work
2826/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2827/// is used by the visitors to those instructions.
2828/// @brief Transforms common to all three rem instructions
2829Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002830 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002831
Chris Lattner50b2ca42008-02-19 06:12:18 +00002832 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002833 if (Constant *LHS = dyn_cast<Constant>(Op0))
2834 if (LHS->isNullValue())
2835 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836
Chris Lattner50b2ca42008-02-19 06:12:18 +00002837 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2838 if (I.getType()->isFPOrFPVector())
2839 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002841 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002842 if (isa<UndefValue>(Op1))
2843 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002844
2845 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002846 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2847 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002848
Reid Spencer0a783f72006-11-02 01:53:59 +00002849 return 0;
2850}
2851
2852/// This function implements the transforms common to both integer remainder
2853/// instructions (urem and srem). It is called by the visitors to those integer
2854/// remainder instructions.
2855/// @brief Common integer remainder transforms
2856Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2857 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859 if (Instruction *common = commonRemTransforms(I))
2860 return common;
2861
Chris Lattner857e8cd2004-12-12 21:48:58 +00002862 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002863 // X % 0 == undef, we don't need to preserve faults!
2864 if (RHS->equalsInt(0))
2865 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2866
Chris Lattnera2881962003-02-18 19:28:33 +00002867 if (RHS->equalsInt(1)) // X % 1 == 0
2868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2869
Chris Lattner97943922006-02-28 05:49:21 +00002870 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2871 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2872 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2873 return R;
2874 } else if (isa<PHINode>(Op0I)) {
2875 if (Instruction *NV = FoldOpIntoPhi(I))
2876 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002877 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002878
2879 // See if we can fold away this rem instruction.
2880 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2881 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2882 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2883 KnownZero, KnownOne))
2884 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002885 }
Chris Lattnera2881962003-02-18 19:28:33 +00002886 }
2887
Reid Spencer0a783f72006-11-02 01:53:59 +00002888 return 0;
2889}
2890
2891Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2893
2894 if (Instruction *common = commonIRemTransforms(I))
2895 return common;
2896
2897 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2898 // X urem C^2 -> X and C
2899 // Check to see if this is an unsigned remainder with an exact power of 2,
2900 // if so, convert to a bitwise and.
2901 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002902 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002903 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002904 }
2905
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002906 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002907 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2908 if (RHSI->getOpcode() == Instruction::Shl &&
2909 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002910 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002911 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002913 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002914 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002915 }
2916 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002917 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002918
Reid Spencer0a783f72006-11-02 01:53:59 +00002919 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2920 // where C1&C2 are powers of two.
2921 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2922 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2923 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2924 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002925 if ((STO->getValue().isPowerOf2()) &&
2926 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002927 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002928 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002929 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002930 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002931 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002932 }
2933 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002934 }
2935
Chris Lattner3f5b8772002-05-06 16:14:14 +00002936 return 0;
2937}
2938
Reid Spencer0a783f72006-11-02 01:53:59 +00002939Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2941
Dan Gohmancff55092007-11-05 23:16:33 +00002942 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002943 if (Instruction *common = commonIRemTransforms(I))
2944 return common;
2945
2946 if (Value *RHSNeg = dyn_castNegVal(Op1))
2947 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002948 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002949 // X % -Y -> X % Y
2950 AddUsesToWorkList(I);
2951 I.setOperand(1, RHSNeg);
2952 return &I;
2953 }
2954
Dan Gohmancff55092007-11-05 23:16:33 +00002955 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002956 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002957 if (I.getType()->isInteger()) {
2958 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2959 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2960 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002961 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002962 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002963 }
2964
2965 return 0;
2966}
2967
2968Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002969 return commonRemTransforms(I);
2970}
2971
Chris Lattner457dd822004-06-09 07:59:58 +00002972// isOneBitSet - Return true if there is exactly one bit set in the specified
2973// constant.
2974static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002975 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002976}
2977
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002978// isHighOnes - Return true if the constant is of the form 1+0+.
2979// This is the same as lowones(~X).
2980static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002981 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002982}
2983
Reid Spencere4d87aa2006-12-23 06:05:41 +00002984/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002985/// are carefully arranged to allow folding of expressions such as:
2986///
2987/// (A < B) | (A > B) --> (A != B)
2988///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002989/// Note that this is only valid if the first and second predicates have the
2990/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002991///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002992/// Three bits are used to represent the condition, as follows:
2993/// 0 A > B
2994/// 1 A == B
2995/// 2 A < B
2996///
2997/// <=> Value Definition
2998/// 000 0 Always false
2999/// 001 1 A > B
3000/// 010 2 A == B
3001/// 011 3 A >= B
3002/// 100 4 A < B
3003/// 101 5 A != B
3004/// 110 6 A <= B
3005/// 111 7 Always true
3006///
3007static unsigned getICmpCode(const ICmpInst *ICI) {
3008 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003009 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003010 case ICmpInst::ICMP_UGT: return 1; // 001
3011 case ICmpInst::ICMP_SGT: return 1; // 001
3012 case ICmpInst::ICMP_EQ: return 2; // 010
3013 case ICmpInst::ICMP_UGE: return 3; // 011
3014 case ICmpInst::ICMP_SGE: return 3; // 011
3015 case ICmpInst::ICMP_ULT: return 4; // 100
3016 case ICmpInst::ICMP_SLT: return 4; // 100
3017 case ICmpInst::ICMP_NE: return 5; // 101
3018 case ICmpInst::ICMP_ULE: return 6; // 110
3019 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003020 // True -> 7
3021 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003022 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003023 return 0;
3024 }
3025}
3026
Reid Spencere4d87aa2006-12-23 06:05:41 +00003027/// getICmpValue - This is the complement of getICmpCode, which turns an
3028/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003029/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003030/// of predicate to use in new icmp instructions.
3031static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3032 switch (code) {
3033 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003034 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003035 case 1:
3036 if (sign)
3037 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3038 else
3039 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3040 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3041 case 3:
3042 if (sign)
3043 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3044 else
3045 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3046 case 4:
3047 if (sign)
3048 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3049 else
3050 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3051 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3052 case 6:
3053 if (sign)
3054 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3055 else
3056 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003057 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003058 }
3059}
3060
Reid Spencere4d87aa2006-12-23 06:05:41 +00003061static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3062 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3063 (ICmpInst::isSignedPredicate(p1) &&
3064 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3065 (ICmpInst::isSignedPredicate(p2) &&
3066 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3067}
3068
3069namespace {
3070// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3071struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003072 InstCombiner &IC;
3073 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003074 ICmpInst::Predicate pred;
3075 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3076 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3077 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003078 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003079 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3080 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003081 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3082 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003083 return false;
3084 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003085 Instruction *apply(Instruction &Log) const {
3086 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3087 if (ICI->getOperand(0) != LHS) {
3088 assert(ICI->getOperand(1) == LHS);
3089 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003090 }
3091
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003092 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003093 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003094 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003095 unsigned Code;
3096 switch (Log.getOpcode()) {
3097 case Instruction::And: Code = LHSCode & RHSCode; break;
3098 case Instruction::Or: Code = LHSCode | RHSCode; break;
3099 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003100 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003101 }
3102
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003103 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3104 ICmpInst::isSignedPredicate(ICI->getPredicate());
3105
3106 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003107 if (Instruction *I = dyn_cast<Instruction>(RV))
3108 return I;
3109 // Otherwise, it's a constant boolean value...
3110 return IC.ReplaceInstUsesWith(Log, RV);
3111 }
3112};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003113} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003114
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003115// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3116// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003117// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003118Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003119 ConstantInt *OpRHS,
3120 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003121 BinaryOperator &TheAnd) {
3122 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003123 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003124 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003125 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003126
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003127 switch (Op->getOpcode()) {
3128 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003129 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003130 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003131 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003132 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003133 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003134 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003135 }
3136 break;
3137 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003138 if (Together == AndRHS) // (X | C) & C --> C
3139 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003140
Chris Lattner6e7ba452005-01-01 16:22:27 +00003141 if (Op->hasOneUse() && Together != OpRHS) {
3142 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003143 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003144 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003145 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003146 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003147 }
3148 break;
3149 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003150 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003151 // Adding a one to a single bit bit-field should be turned into an XOR
3152 // of the bit. First thing to check is to see if this AND is with a
3153 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003154 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003155
3156 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003157 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003158 // Ok, at this point, we know that we are masking the result of the
3159 // ADD down to exactly one bit. If the constant we are adding has
3160 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003161 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003162
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003163 // Check to see if any bits below the one bit set in AndRHSV are set.
3164 if ((AddRHS & (AndRHSV-1)) == 0) {
3165 // If not, the only thing that can effect the output of the AND is
3166 // the bit specified by AndRHSV. If that bit is set, the effect of
3167 // the XOR is to toggle the bit. If it is clear, then the ADD has
3168 // no effect.
3169 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3170 TheAnd.setOperand(0, X);
3171 return &TheAnd;
3172 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003173 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003174 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003175 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003176 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003177 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003178 }
3179 }
3180 }
3181 }
3182 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003183
3184 case Instruction::Shl: {
3185 // We know that the AND will not produce any of the bits shifted in, so if
3186 // the anded constant includes them, clear them now!
3187 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003188 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003189 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003190 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3191 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003192
Zhou Sheng290bec52007-03-29 08:15:12 +00003193 if (CI->getValue() == ShlMask) {
3194 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003195 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3196 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003197 TheAnd.setOperand(1, CI);
3198 return &TheAnd;
3199 }
3200 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003201 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003202 case Instruction::LShr:
3203 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003204 // We know that the AND will not produce any of the bits shifted in, so if
3205 // the anded constant includes them, clear them now! This only applies to
3206 // unsigned shifts, because a signed shr may bring in set bits!
3207 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003208 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003209 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003210 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3211 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003212
Zhou Sheng290bec52007-03-29 08:15:12 +00003213 if (CI->getValue() == ShrMask) {
3214 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003215 return ReplaceInstUsesWith(TheAnd, Op);
3216 } else if (CI != AndRHS) {
3217 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3218 return &TheAnd;
3219 }
3220 break;
3221 }
3222 case Instruction::AShr:
3223 // Signed shr.
3224 // See if this is shifting in some sign extension, then masking it out
3225 // with an and.
3226 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003227 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003228 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003229 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3230 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003231 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003232 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003233 // Make the argument unsigned.
3234 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003235 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003236 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003237 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003238 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003239 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003240 }
3241 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003242 }
3243 return 0;
3244}
3245
Chris Lattner8b170942002-08-09 23:47:40 +00003246
Chris Lattnera96879a2004-09-29 17:40:11 +00003247/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3248/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003249/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3250/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003251/// insert new instructions.
3252Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003253 bool isSigned, bool Inside,
3254 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003255 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003256 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003257 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258
Chris Lattnera96879a2004-09-29 17:40:11 +00003259 if (Inside) {
3260 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003261 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003262
Reid Spencere4d87aa2006-12-23 06:05:41 +00003263 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003264 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003265 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003266 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3267 return new ICmpInst(pred, V, Hi);
3268 }
3269
3270 // Emit V-Lo <u Hi-Lo
3271 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003272 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003273 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003274 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3275 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003276 }
3277
3278 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003279 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003280
Reid Spencere4e40032007-03-21 23:19:50 +00003281 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003282 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003283 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284 ICmpInst::Predicate pred = (isSigned ?
3285 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3286 return new ICmpInst(pred, V, Hi);
3287 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003288
Reid Spencere4e40032007-03-21 23:19:50 +00003289 // Emit V-Lo >u Hi-1-Lo
3290 // Note that Hi has already had one subtracted from it, above.
3291 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003292 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003293 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003294 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3295 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003296}
3297
Chris Lattner7203e152005-09-18 07:22:02 +00003298// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3299// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3300// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3301// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003302static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003303 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003304 uint32_t BitWidth = Val->getType()->getBitWidth();
3305 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003306
3307 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003308 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003309 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003310 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003311 return true;
3312}
3313
Chris Lattner7203e152005-09-18 07:22:02 +00003314/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3315/// where isSub determines whether the operator is a sub. If we can fold one of
3316/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003317///
3318/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3319/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3320/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3321///
3322/// return (A +/- B).
3323///
3324Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003325 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003326 Instruction &I) {
3327 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3328 if (!LHSI || LHSI->getNumOperands() != 2 ||
3329 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3330
3331 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3332
3333 switch (LHSI->getOpcode()) {
3334 default: return 0;
3335 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003336 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003337 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003338 if ((Mask->getValue().countLeadingZeros() +
3339 Mask->getValue().countPopulation()) ==
3340 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003341 break;
3342
3343 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3344 // part, we don't need any explicit masks to take them out of A. If that
3345 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003346 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003347 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003348 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003349 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003350 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003351 break;
3352 }
3353 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003354 return 0;
3355 case Instruction::Or:
3356 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003357 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003358 if ((Mask->getValue().countLeadingZeros() +
3359 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003360 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003361 break;
3362 return 0;
3363 }
3364
3365 Instruction *New;
3366 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003367 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003368 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003369 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003370 return InsertNewInstBefore(New, I);
3371}
3372
Chris Lattner7e708292002-06-25 16:13:24 +00003373Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003374 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003376
Chris Lattnere87597f2004-10-16 18:11:37 +00003377 if (isa<UndefValue>(Op1)) // X & undef -> 0
3378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3379
Chris Lattner6e7ba452005-01-01 16:22:27 +00003380 // and X, X = X
3381 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003382 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003383
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003384 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003385 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003386 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003387 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3389 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003390 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003391 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003392 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003393 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003394 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003395 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003396 } else if (isa<ConstantAggregateZero>(Op1)) {
3397 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003398 }
3399 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003400
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003401 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003402 const APInt& AndRHSMask = AndRHS->getValue();
3403 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003404
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003405 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003406 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003407 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003408 Value *Op0LHS = Op0I->getOperand(0);
3409 Value *Op0RHS = Op0I->getOperand(1);
3410 switch (Op0I->getOpcode()) {
3411 case Instruction::Xor:
3412 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003413 // If the mask is only needed on one incoming arm, push it up.
3414 if (Op0I->hasOneUse()) {
3415 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3416 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003417 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003418 Op0RHS->getName()+".masked");
3419 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003420 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003421 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003422 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003423 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003424 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3425 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003426 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003427 Op0LHS->getName()+".masked");
3428 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003429 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003430 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3431 }
3432 }
3433
Chris Lattner6e7ba452005-01-01 16:22:27 +00003434 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003435 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003436 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3437 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3438 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3439 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003440 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003441 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003442 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003443 break;
3444
3445 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003446 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3447 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3448 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3449 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003450 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003451
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003452 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3453 // has 1's for all bits that the subtraction with A might affect.
3454 if (Op0I->hasOneUse()) {
3455 uint32_t BitWidth = AndRHSMask.getBitWidth();
3456 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3457 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3458
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003459 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003460 if (!(A && A->isZero()) && // avoid infinite recursion.
3461 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003462 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3463 InsertNewInstBefore(NewNeg, I);
3464 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3465 }
3466 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003467 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003468
3469 case Instruction::Shl:
3470 case Instruction::LShr:
3471 // (1 << x) & 1 --> zext(x == 0)
3472 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003473 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003474 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3475 Constant::getNullValue(I.getType()));
3476 InsertNewInstBefore(NewICmp, I);
3477 return new ZExtInst(NewICmp, I.getType());
3478 }
3479 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003480 }
3481
Chris Lattner58403262003-07-23 19:25:52 +00003482 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003483 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003484 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003485 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003486 // If this is an integer truncation or change from signed-to-unsigned, and
3487 // if the source is an and/or with immediate, transform it. This
3488 // frequently occurs for bitfield accesses.
3489 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003490 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003491 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003492 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003493 if (CastOp->getOpcode() == Instruction::And) {
3494 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003495 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3496 // This will fold the two constants together, which may allow
3497 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003498 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003499 CastOp->getOperand(0), I.getType(),
3500 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003501 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003502 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003503 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003504 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003505 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003506 } else if (CastOp->getOpcode() == Instruction::Or) {
3507 // Change: and (cast (or X, C1) to T), C2
3508 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003509 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003510 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3511 return ReplaceInstUsesWith(I, AndRHS);
3512 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003513 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003514 }
Chris Lattner06782f82003-07-23 19:36:21 +00003515 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003516
3517 // Try to fold constant and into select arguments.
3518 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003519 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003520 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003521 if (isa<PHINode>(Op0))
3522 if (Instruction *NV = FoldOpIntoPhi(I))
3523 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003524 }
3525
Chris Lattner8d969642003-03-10 23:06:50 +00003526 Value *Op0NotVal = dyn_castNotVal(Op0);
3527 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003528
Chris Lattner5b62aa72004-06-18 06:07:51 +00003529 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3530 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3531
Misha Brukmancb6267b2004-07-30 12:50:08 +00003532 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003533 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003534 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003535 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003536 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003538 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003539
3540 {
Chris Lattner003b6202007-06-15 05:58:24 +00003541 Value *A = 0, *B = 0, *C = 0, *D = 0;
3542 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003543 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3544 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003545
3546 // (A|B) & ~(A&B) -> A^B
3547 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3548 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003550 }
3551 }
3552
3553 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003554 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3555 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003556
3557 // ~(A&B) & (A|B) -> A^B
3558 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3559 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003561 }
3562 }
Chris Lattner64daab52006-04-01 08:03:55 +00003563
3564 if (Op0->hasOneUse() &&
3565 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3566 if (A == Op1) { // (A^B)&A -> A&(A^B)
3567 I.swapOperands(); // Simplify below
3568 std::swap(Op0, Op1);
3569 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3570 cast<BinaryOperator>(Op0)->swapOperands();
3571 I.swapOperands(); // Simplify below
3572 std::swap(Op0, Op1);
3573 }
3574 }
3575 if (Op1->hasOneUse() &&
3576 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3577 if (B == Op0) { // B&(A^B) -> B&(B^A)
3578 cast<BinaryOperator>(Op1)->swapOperands();
3579 std::swap(A, B);
3580 }
3581 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003583 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003584 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003585 }
3586 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003587 }
3588
Nick Lewycky9ee863e2008-07-09 07:29:11 +00003589
3590 { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3591 // where C is a power of 2
3592 Value *A, *B;
3593 ConstantInt *C1, *C2;
3594 ICmpInst::Predicate LHSCC, RHSCC;
3595 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3596 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3597 if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3598 (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3599 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3600 InsertNewInstBefore(NewOr, I);
3601 return new ICmpInst(LHSCC, NewOr, C1);
3602 }
3603 }
3604
Reid Spencere4d87aa2006-12-23 06:05:41 +00003605 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3606 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3607 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003608 return R;
3609
Chris Lattner955f3312004-09-28 21:48:02 +00003610 Value *LHSVal, *RHSVal;
3611 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003612 ICmpInst::Predicate LHSCC, RHSCC;
3613 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3614 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3615 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3616 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3617 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3618 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3619 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003620 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3621
3622 // Don't try to fold ICMP_SLT + ICMP_ULT.
3623 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3624 ICmpInst::isSignedPredicate(LHSCC) ==
3625 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003626 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003627 ICmpInst::Predicate GT;
3628 if (ICmpInst::isSignedPredicate(LHSCC) ||
3629 (ICmpInst::isEquality(LHSCC) &&
3630 ICmpInst::isSignedPredicate(RHSCC)))
3631 GT = ICmpInst::ICMP_SGT;
3632 else
3633 GT = ICmpInst::ICMP_UGT;
3634
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3636 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003637 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003638 std::swap(LHS, RHS);
3639 std::swap(LHSCst, RHSCst);
3640 std::swap(LHSCC, RHSCC);
3641 }
3642
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003644 // comparing a value against two constants and and'ing the result
3645 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3647 // (from the FoldICmpLogical check above), that the two constants
3648 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003649 assert(LHSCst != RHSCst && "Compares not folded above?");
3650
3651 switch (LHSCC) {
3652 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003654 switch (RHSCC) {
3655 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3657 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3658 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003659 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3661 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3662 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003663 return ReplaceInstUsesWith(I, LHS);
3664 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003666 switch (RHSCC) {
3667 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 case ICmpInst::ICMP_ULT:
3669 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3670 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3671 break; // (X != 13 & X u< 15) -> no change
3672 case ICmpInst::ICMP_SLT:
3673 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3674 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3675 break; // (X != 13 & X s< 15) -> no change
3676 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3677 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3678 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003679 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680 case ICmpInst::ICMP_NE:
3681 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003682 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003683 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003684 LHSVal->getName()+".off");
3685 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003686 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3687 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003688 }
3689 break; // (X != 13 & X != 15) -> no change
3690 }
3691 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003693 switch (RHSCC) {
3694 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3696 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003697 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3699 break;
3700 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3701 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003702 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3704 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003705 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 break;
3707 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003708 switch (RHSCC) {
3709 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3711 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003712 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003713 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3714 break;
3715 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3716 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003717 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3719 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003720 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003721 break;
3722 case ICmpInst::ICMP_UGT:
3723 switch (RHSCC) {
3724 default: assert(0 && "Unknown integer condition code!");
Eli Friedman5c1f1722008-06-21 23:36:13 +00003725 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003726 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3727 return ReplaceInstUsesWith(I, RHS);
3728 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3729 break;
3730 case ICmpInst::ICMP_NE:
3731 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3732 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3733 break; // (X u> 13 & X != 15) -> no change
3734 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3735 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3736 true, I);
3737 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3738 break;
3739 }
3740 break;
3741 case ICmpInst::ICMP_SGT:
3742 switch (RHSCC) {
3743 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003744 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003745 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3746 return ReplaceInstUsesWith(I, RHS);
3747 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3748 break;
3749 case ICmpInst::ICMP_NE:
3750 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3751 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3752 break; // (X s> 13 & X != 15) -> no change
3753 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3754 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3755 true, I);
3756 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3757 break;
3758 }
3759 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003760 }
3761 }
3762 }
3763
Chris Lattner6fc205f2006-05-05 06:39:07 +00003764 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003765 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3766 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3767 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3768 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003769 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003770 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003771 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3772 I.getType(), TD) &&
3773 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3774 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003775 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003776 Op1C->getOperand(0),
3777 I.getName());
3778 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003779 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003780 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003781 }
Chris Lattnere511b742006-11-14 07:46:50 +00003782
3783 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003784 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3785 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3786 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003787 SI0->getOperand(1) == SI1->getOperand(1) &&
3788 (SI0->hasOneUse() || SI1->hasOneUse())) {
3789 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003790 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003791 SI1->getOperand(0),
3792 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003793 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003794 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003795 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003796 }
3797
Chris Lattner99c65742007-10-24 05:38:08 +00003798 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3799 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3800 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3801 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3802 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3803 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3804 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3805 // If either of the constants are nans, then the whole thing returns
3806 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003807 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003808 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3809 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3810 RHS->getOperand(0));
3811 }
3812 }
3813 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003814
Chris Lattner7e708292002-06-25 16:13:24 +00003815 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003816}
3817
Chris Lattnerafe91a52006-06-15 19:07:26 +00003818/// CollectBSwapParts - Look to see if the specified value defines a single byte
3819/// in the result. If it does, and if the specified byte hasn't been filled in
3820/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003821static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003822 Instruction *I = dyn_cast<Instruction>(V);
3823 if (I == 0) return true;
3824
3825 // If this is an or instruction, it is an inner node of the bswap.
3826 if (I->getOpcode() == Instruction::Or)
3827 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3828 CollectBSwapParts(I->getOperand(1), ByteValues);
3829
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003830 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003831 // If this is a shift by a constant int, and it is "24", then its operand
3832 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003833 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003834 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003835 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003836 8*(ByteValues.size()-1))
3837 return true;
3838
3839 unsigned DestNo;
3840 if (I->getOpcode() == Instruction::Shl) {
3841 // X << 24 defines the top byte with the lowest of the input bytes.
3842 DestNo = ByteValues.size()-1;
3843 } else {
3844 // X >>u 24 defines the low byte with the highest of the input bytes.
3845 DestNo = 0;
3846 }
3847
3848 // If the destination byte value is already defined, the values are or'd
3849 // together, which isn't a bswap (unless it's an or of the same bits).
3850 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3851 return true;
3852 ByteValues[DestNo] = I->getOperand(0);
3853 return false;
3854 }
3855
3856 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3857 // don't have this.
3858 Value *Shift = 0, *ShiftLHS = 0;
3859 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3860 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3861 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3862 return true;
3863 Instruction *SI = cast<Instruction>(Shift);
3864
3865 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003866 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3867 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003868 return true;
3869
3870 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3871 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003872 if (AndAmt->getValue().getActiveBits() > 64)
3873 return true;
3874 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003875 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003876 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003877 break;
3878 // Unknown mask for bswap.
3879 if (DestByte == ByteValues.size()) return true;
3880
Reid Spencerb83eb642006-10-20 07:07:24 +00003881 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003882 unsigned SrcByte;
3883 if (SI->getOpcode() == Instruction::Shl)
3884 SrcByte = DestByte - ShiftBytes;
3885 else
3886 SrcByte = DestByte + ShiftBytes;
3887
3888 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3889 if (SrcByte != ByteValues.size()-DestByte-1)
3890 return true;
3891
3892 // If the destination byte value is already defined, the values are or'd
3893 // together, which isn't a bswap (unless it's an or of the same bits).
3894 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3895 return true;
3896 ByteValues[DestByte] = SI->getOperand(0);
3897 return false;
3898}
3899
3900/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3901/// If so, insert the new bswap intrinsic and return it.
3902Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003903 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3904 if (!ITy || ITy->getBitWidth() % 16)
3905 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003906
3907 /// ByteValues - For each byte of the result, we keep track of which value
3908 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003909 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003910 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003911
3912 // Try to find all the pieces corresponding to the bswap.
3913 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3914 CollectBSwapParts(I.getOperand(1), ByteValues))
3915 return 0;
3916
3917 // Check to see if all of the bytes come from the same value.
3918 Value *V = ByteValues[0];
3919 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3920
3921 // Check to make sure that all of the bytes come from the same value.
3922 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3923 if (ByteValues[i] != V)
3924 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003925 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003926 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003927 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003928 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003929}
3930
3931
Chris Lattner7e708292002-06-25 16:13:24 +00003932Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003933 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003935
Chris Lattner42593e62007-03-24 23:56:43 +00003936 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003937 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003938
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003939 // or X, X = X
3940 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003941 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003942
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003943 // See if we can simplify any instructions used by the instruction whose sole
3944 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003945 if (!isa<VectorType>(I.getType())) {
3946 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3947 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3948 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3949 KnownZero, KnownOne))
3950 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003951 } else if (isa<ConstantAggregateZero>(Op1)) {
3952 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3953 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3954 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3955 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003956 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003957
3958
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003959
Chris Lattner3f5b8772002-05-06 16:14:14 +00003960 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003961 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003962 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003963 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3964 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003965 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003966 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003967 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003968 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003969 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003970 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003971
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003972 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3973 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003974 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003975 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003976 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003977 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003978 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003979 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003980
3981 // Try to fold constant and into select arguments.
3982 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003983 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003984 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003985 if (isa<PHINode>(Op0))
3986 if (Instruction *NV = FoldOpIntoPhi(I))
3987 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003988 }
3989
Chris Lattner4f637d42006-01-06 17:59:59 +00003990 Value *A = 0, *B = 0;
3991 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003992
3993 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3994 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3995 return ReplaceInstUsesWith(I, Op1);
3996 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3997 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3998 return ReplaceInstUsesWith(I, Op0);
3999
Chris Lattner6423d4c2006-07-10 20:25:24 +00004000 // (A | B) | C and A | (B | C) -> bswap if possible.
4001 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004002 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004003 match(Op1, m_Or(m_Value(), m_Value())) ||
4004 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4005 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004006 if (Instruction *BSwap = MatchBSwap(I))
4007 return BSwap;
4008 }
4009
Chris Lattner6e4c6492005-05-09 04:58:36 +00004010 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4011 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004012 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004013 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004014 InsertNewInstBefore(NOr, I);
4015 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004016 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004017 }
4018
4019 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4020 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004021 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004022 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004023 InsertNewInstBefore(NOr, I);
4024 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004026 }
4027
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004028 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004029 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004030 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4031 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004032 Value *V1 = 0, *V2 = 0, *V3 = 0;
4033 C1 = dyn_cast<ConstantInt>(C);
4034 C2 = dyn_cast<ConstantInt>(D);
4035 if (C1 && C2) { // (A & C1)|(B & C2)
4036 // If we have: ((V + N) & C1) | (V & C2)
4037 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4038 // replace with V+N.
4039 if (C1->getValue() == ~C2->getValue()) {
4040 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4041 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4042 // Add commutes, try both ways.
4043 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4044 return ReplaceInstUsesWith(I, A);
4045 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4046 return ReplaceInstUsesWith(I, A);
4047 }
4048 // Or commutes, try both ways.
4049 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4050 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4051 // Add commutes, try both ways.
4052 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4053 return ReplaceInstUsesWith(I, B);
4054 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4055 return ReplaceInstUsesWith(I, B);
4056 }
4057 }
Chris Lattner044e5332007-04-08 08:01:49 +00004058 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004059 }
4060
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004061 // Check to see if we have any common things being and'ed. If so, find the
4062 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004063 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4064 if (A == B) // (A & C)|(A & D) == A & (C|D)
4065 V1 = A, V2 = C, V3 = D;
4066 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4067 V1 = A, V2 = B, V3 = C;
4068 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4069 V1 = C, V2 = A, V3 = D;
4070 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4071 V1 = C, V2 = A, V3 = B;
4072
4073 if (V1) {
4074 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004075 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4076 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004077 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004078 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004079 }
Chris Lattnere511b742006-11-14 07:46:50 +00004080
4081 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004082 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4083 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4084 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004085 SI0->getOperand(1) == SI1->getOperand(1) &&
4086 (SI0->hasOneUse() || SI1->hasOneUse())) {
4087 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004089 SI1->getOperand(0),
4090 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004092 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004093 }
4094 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004095
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004096 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4097 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004098 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004099 } else {
4100 A = 0;
4101 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004102 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004103 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4104 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004105 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004106
Misha Brukmancb6267b2004-07-30 12:50:08 +00004107 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004108 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004109 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004110 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004111 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004112 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004113 }
Chris Lattnera2881962003-02-18 19:28:33 +00004114
Reid Spencere4d87aa2006-12-23 06:05:41 +00004115 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4116 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4117 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004118 return R;
4119
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004120 Value *LHSVal, *RHSVal;
4121 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004122 ICmpInst::Predicate LHSCC, RHSCC;
4123 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4124 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4125 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4126 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4127 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4128 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4129 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004130 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4131 // We can't fold (ugt x, C) | (sgt x, C2).
4132 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004133 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004134 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004135 bool NeedsSwap;
4136 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004137 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004138 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004139 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004140
4141 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004142 std::swap(LHS, RHS);
4143 std::swap(LHSCst, RHSCst);
4144 std::swap(LHSCC, RHSCC);
4145 }
4146
Reid Spencere4d87aa2006-12-23 06:05:41 +00004147 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004148 // comparing a value against two constants and or'ing the result
4149 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004150 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4151 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004152 // equal.
4153 assert(LHSCst != RHSCst && "Compares not folded above?");
4154
4155 switch (LHSCC) {
4156 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004157 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004158 switch (RHSCC) {
4159 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004160 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004161 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4162 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004163 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004164 LHSVal->getName()+".off");
4165 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004166 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004167 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004168 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004169 break; // (X == 13 | X == 15) -> no change
4170 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4171 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004172 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4174 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4175 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004176 return ReplaceInstUsesWith(I, RHS);
4177 }
4178 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004179 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004180 switch (RHSCC) {
4181 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004182 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4183 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4184 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004185 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004186 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4187 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4188 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004189 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004190 }
4191 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004193 switch (RHSCC) {
4194 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004196 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004197 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004198 // If RHSCst is [us]MAXINT, it is always false. Not handling
4199 // this can cause overflow.
4200 if (RHSCst->isMaxValue(false))
4201 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004202 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4203 false, I);
4204 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4205 break;
4206 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4207 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004208 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4210 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004211 }
4212 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004213 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004214 switch (RHSCC) {
4215 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004216 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4217 break;
4218 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004219 // If RHSCst is [us]MAXINT, it is always false. Not handling
4220 // this can cause overflow.
4221 if (RHSCst->isMaxValue(true))
4222 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004223 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4224 false, I);
4225 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4226 break;
4227 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4228 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4229 return ReplaceInstUsesWith(I, RHS);
4230 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4231 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004232 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004233 break;
4234 case ICmpInst::ICMP_UGT:
4235 switch (RHSCC) {
4236 default: assert(0 && "Unknown integer condition code!");
4237 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4238 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4239 return ReplaceInstUsesWith(I, LHS);
4240 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4241 break;
4242 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4243 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004244 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004245 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4246 break;
4247 }
4248 break;
4249 case ICmpInst::ICMP_SGT:
4250 switch (RHSCC) {
4251 default: assert(0 && "Unknown integer condition code!");
4252 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4253 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4254 return ReplaceInstUsesWith(I, LHS);
4255 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4256 break;
4257 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4258 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004259 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004260 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4261 break;
4262 }
4263 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004264 }
4265 }
4266 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004267
4268 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004269 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004270 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004271 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004272 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4273 !isa<ICmpInst>(Op1C->getOperand(0))) {
4274 const Type *SrcTy = Op0C->getOperand(0)->getType();
4275 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4276 // Only do this if the casts both really cause code to be
4277 // generated.
4278 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4279 I.getType(), TD) &&
4280 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4281 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004282 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004283 Op1C->getOperand(0),
4284 I.getName());
4285 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004286 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004287 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004288 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004289 }
Chris Lattner99c65742007-10-24 05:38:08 +00004290 }
4291
4292
4293 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4294 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4295 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4296 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004297 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4298 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004299 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4300 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4301 // If either of the constants are nans, then the whole thing returns
4302 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004303 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004304 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4305
4306 // Otherwise, no need to compare the two constants, compare the
4307 // rest.
4308 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4309 RHS->getOperand(0));
4310 }
4311 }
4312 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004313
Chris Lattner7e708292002-06-25 16:13:24 +00004314 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004315}
4316
Dan Gohman844731a2008-05-13 00:00:25 +00004317namespace {
4318
Chris Lattnerc317d392004-02-16 01:20:27 +00004319// XorSelf - Implements: X ^ X --> 0
4320struct XorSelf {
4321 Value *RHS;
4322 XorSelf(Value *rhs) : RHS(rhs) {}
4323 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4324 Instruction *apply(BinaryOperator &Xor) const {
4325 return &Xor;
4326 }
4327};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004328
Dan Gohman844731a2008-05-13 00:00:25 +00004329}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004330
Chris Lattner7e708292002-06-25 16:13:24 +00004331Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004332 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004333 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004334
Evan Chengd34af782008-03-25 20:07:13 +00004335 if (isa<UndefValue>(Op1)) {
4336 if (isa<UndefValue>(Op0))
4337 // Handle undef ^ undef -> 0 special case. This is a common
4338 // idiom (misuse).
4339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004340 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004341 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004342
Chris Lattnerc317d392004-02-16 01:20:27 +00004343 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4344 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004345 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004347 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004348
4349 // See if we can simplify any instructions used by the instruction whose sole
4350 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004351 if (!isa<VectorType>(I.getType())) {
4352 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4353 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4354 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4355 KnownZero, KnownOne))
4356 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004357 } else if (isa<ConstantAggregateZero>(Op1)) {
4358 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004359 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004360
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004361 // Is this a ~ operation?
4362 if (Value *NotOp = dyn_castNotVal(&I)) {
4363 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4364 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4365 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4366 if (Op0I->getOpcode() == Instruction::And ||
4367 Op0I->getOpcode() == Instruction::Or) {
4368 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4369 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4370 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004371 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004372 Op0I->getOperand(1)->getName()+".not");
4373 InsertNewInstBefore(NotY, I);
4374 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004375 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004376 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004377 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004378 }
4379 }
4380 }
4381 }
4382
4383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004384 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004385 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4386 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4387 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004388 return new ICmpInst(ICI->getInversePredicate(),
4389 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004390
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004391 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4392 return new FCmpInst(FCI->getInversePredicate(),
4393 FCI->getOperand(0), FCI->getOperand(1));
4394 }
4395
Nick Lewycky517e1f52008-05-31 19:01:33 +00004396 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4397 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4398 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4399 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4400 Instruction::CastOps Opcode = Op0C->getOpcode();
4401 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4402 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4403 Op0C->getDestTy())) {
4404 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4405 CI->getOpcode(), CI->getInversePredicate(),
4406 CI->getOperand(0), CI->getOperand(1)), I);
4407 NewCI->takeName(CI);
4408 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4409 }
4410 }
4411 }
4412 }
4413 }
4414
Reid Spencere4d87aa2006-12-23 06:05:41 +00004415 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004416 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004417 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4418 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004419 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4420 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004421 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004422 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004423 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004424
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004425 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004426 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004427 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004428 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004429 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004430 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004431 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004432 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004433 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004434 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004435 // (X + C) ^ signbit -> (X + C + signbit)
4436 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004437 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004438
Chris Lattner7c4049c2004-01-12 19:35:11 +00004439 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004440 } else if (Op0I->getOpcode() == Instruction::Or) {
4441 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004442 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004443 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4444 // Anything in both C1 and C2 is known to be zero, remove it from
4445 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004446 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004447 NewRHS = ConstantExpr::getAnd(NewRHS,
4448 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004449 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004450 I.setOperand(0, Op0I->getOperand(0));
4451 I.setOperand(1, NewRHS);
4452 return &I;
4453 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004454 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004455 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004456 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004457
4458 // Try to fold constant and into select arguments.
4459 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004461 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004462 if (isa<PHINode>(Op0))
4463 if (Instruction *NV = FoldOpIntoPhi(I))
4464 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004465 }
4466
Chris Lattner8d969642003-03-10 23:06:50 +00004467 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004468 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004469 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004470
Chris Lattner8d969642003-03-10 23:06:50 +00004471 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004472 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004473 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004474
Chris Lattner318bf792007-03-18 22:51:34 +00004475
4476 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4477 if (Op1I) {
4478 Value *A, *B;
4479 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4480 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004481 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004482 I.swapOperands();
4483 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004484 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004485 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004486 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004487 }
Chris Lattner318bf792007-03-18 22:51:34 +00004488 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4489 if (Op0 == A) // A^(A^B) == B
4490 return ReplaceInstUsesWith(I, B);
4491 else if (Op0 == B) // A^(B^A) == B
4492 return ReplaceInstUsesWith(I, A);
4493 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004494 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004495 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004496 std::swap(A, B);
4497 }
Chris Lattner318bf792007-03-18 22:51:34 +00004498 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004499 I.swapOperands(); // Simplified below.
4500 std::swap(Op0, Op1);
4501 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004502 }
Chris Lattner318bf792007-03-18 22:51:34 +00004503 }
4504
4505 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4506 if (Op0I) {
4507 Value *A, *B;
4508 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4509 if (A == Op1) // (B|A)^B == (A|B)^B
4510 std::swap(A, B);
4511 if (B == Op1) { // (A|B)^B == A & ~B
4512 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004513 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4514 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004515 }
Chris Lattner318bf792007-03-18 22:51:34 +00004516 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4517 if (Op1 == A) // (A^B)^A == B
4518 return ReplaceInstUsesWith(I, B);
4519 else if (Op1 == B) // (B^A)^A == B
4520 return ReplaceInstUsesWith(I, A);
4521 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4522 if (A == Op1) // (A&B)^A -> (B&A)^A
4523 std::swap(A, B);
4524 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004525 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004526 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004527 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4528 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004529 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004530 }
Chris Lattner318bf792007-03-18 22:51:34 +00004531 }
4532
4533 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4534 if (Op0I && Op1I && Op0I->isShift() &&
4535 Op0I->getOpcode() == Op1I->getOpcode() &&
4536 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4537 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4538 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004539 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004540 Op1I->getOperand(0),
4541 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004542 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004543 Op1I->getOperand(1));
4544 }
4545
4546 if (Op0I && Op1I) {
4547 Value *A, *B, *C, *D;
4548 // (A & B)^(A | B) -> A ^ B
4549 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4550 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4551 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004552 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004553 }
4554 // (A | B)^(A & B) -> A ^ B
4555 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4556 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4557 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004558 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004559 }
4560
4561 // (A & B)^(C & D)
4562 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4563 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4564 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4565 // (X & Y)^(X & Y) -> (Y^Z) & X
4566 Value *X = 0, *Y = 0, *Z = 0;
4567 if (A == C)
4568 X = A, Y = B, Z = D;
4569 else if (A == D)
4570 X = A, Y = B, Z = C;
4571 else if (B == C)
4572 X = B, Y = A, Z = D;
4573 else if (B == D)
4574 X = B, Y = A, Z = C;
4575
4576 if (X) {
4577 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004578 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4579 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004580 }
4581 }
4582 }
4583
Reid Spencere4d87aa2006-12-23 06:05:41 +00004584 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4585 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4586 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004587 return R;
4588
Chris Lattner6fc205f2006-05-05 06:39:07 +00004589 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004590 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004591 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004592 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4593 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004594 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004595 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004596 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4597 I.getType(), TD) &&
4598 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4599 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004600 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004601 Op1C->getOperand(0),
4602 I.getName());
4603 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004604 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004605 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004606 }
Chris Lattner99c65742007-10-24 05:38:08 +00004607 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004608
Chris Lattner7e708292002-06-25 16:13:24 +00004609 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004610}
4611
Chris Lattnera96879a2004-09-29 17:40:11 +00004612/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4613/// overflowed for this type.
4614static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004615 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004616 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004617
Reid Spencere4e40032007-03-21 23:19:50 +00004618 if (IsSigned)
4619 if (In2->getValue().isNegative())
4620 return Result->getValue().sgt(In1->getValue());
4621 else
4622 return Result->getValue().slt(In1->getValue());
4623 else
4624 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004625}
4626
Chris Lattner574da9b2005-01-13 20:14:25 +00004627/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4628/// code necessary to compute the offset from the base pointer (without adding
4629/// in the base pointer). Return the result as a signed integer of intptr size.
4630static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4631 TargetData &TD = IC.getTargetData();
4632 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004633 const Type *IntPtrTy = TD.getIntPtrType();
4634 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004635
4636 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004637 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004638 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004639
Gabor Greif177dd3f2008-06-12 21:37:33 +00004640 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4641 ++i, ++GTI) {
4642 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004643 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004644 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4645 if (OpC->isZero()) continue;
4646
4647 // Handle a struct index, which adds its field offset to the pointer.
4648 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4649 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4650
4651 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4652 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004653 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004654 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004655 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004656 ConstantInt::get(IntPtrTy, Size),
4657 GEP->getName()+".offs"), I);
4658 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004659 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004660
4661 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4662 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4663 Scale = ConstantExpr::getMul(OC, Scale);
4664 if (Constant *RC = dyn_cast<Constant>(Result))
4665 Result = ConstantExpr::getAdd(RC, Scale);
4666 else {
4667 // Emit an add instruction.
4668 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004669 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004670 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004671 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004672 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004673 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004674 // Convert to correct type.
4675 if (Op->getType() != IntPtrTy) {
4676 if (Constant *OpC = dyn_cast<Constant>(Op))
4677 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4678 else
4679 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4680 Op->getName()+".c"), I);
4681 }
4682 if (Size != 1) {
4683 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4684 if (Constant *OpC = dyn_cast<Constant>(Op))
4685 Op = ConstantExpr::getMul(OpC, Scale);
4686 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004687 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004688 GEP->getName()+".idx"), I);
4689 }
4690
4691 // Emit an add instruction.
4692 if (isa<Constant>(Op) && isa<Constant>(Result))
4693 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4694 cast<Constant>(Result));
4695 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004696 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004697 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004698 }
4699 return Result;
4700}
4701
Chris Lattner10c0d912008-04-22 02:53:33 +00004702
4703/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4704/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4705/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4706/// complex, and scales are involved. The above expression would also be legal
4707/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4708/// later form is less amenable to optimization though, and we are allowed to
4709/// generate the first by knowing that pointer arithmetic doesn't overflow.
4710///
4711/// If we can't emit an optimized form for this expression, this returns null.
4712///
4713static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4714 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004715 TargetData &TD = IC.getTargetData();
4716 gep_type_iterator GTI = gep_type_begin(GEP);
4717
4718 // Check to see if this gep only has a single variable index. If so, and if
4719 // any constant indices are a multiple of its scale, then we can compute this
4720 // in terms of the scale of the variable index. For example, if the GEP
4721 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4722 // because the expression will cross zero at the same point.
4723 unsigned i, e = GEP->getNumOperands();
4724 int64_t Offset = 0;
4725 for (i = 1; i != e; ++i, ++GTI) {
4726 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4727 // Compute the aggregate offset of constant indices.
4728 if (CI->isZero()) continue;
4729
4730 // Handle a struct index, which adds its field offset to the pointer.
4731 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4732 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4733 } else {
4734 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4735 Offset += Size*CI->getSExtValue();
4736 }
4737 } else {
4738 // Found our variable index.
4739 break;
4740 }
4741 }
4742
4743 // If there are no variable indices, we must have a constant offset, just
4744 // evaluate it the general way.
4745 if (i == e) return 0;
4746
4747 Value *VariableIdx = GEP->getOperand(i);
4748 // Determine the scale factor of the variable element. For example, this is
4749 // 4 if the variable index is into an array of i32.
4750 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4751
4752 // Verify that there are no other variable indices. If so, emit the hard way.
4753 for (++i, ++GTI; i != e; ++i, ++GTI) {
4754 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4755 if (!CI) return 0;
4756
4757 // Compute the aggregate offset of constant indices.
4758 if (CI->isZero()) continue;
4759
4760 // Handle a struct index, which adds its field offset to the pointer.
4761 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4762 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4763 } else {
4764 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4765 Offset += Size*CI->getSExtValue();
4766 }
4767 }
4768
4769 // Okay, we know we have a single variable index, which must be a
4770 // pointer/array/vector index. If there is no offset, life is simple, return
4771 // the index.
4772 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4773 if (Offset == 0) {
4774 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4775 // we don't need to bother extending: the extension won't affect where the
4776 // computation crosses zero.
4777 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4778 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4779 VariableIdx->getNameStart(), &I);
4780 return VariableIdx;
4781 }
4782
4783 // Otherwise, there is an index. The computation we will do will be modulo
4784 // the pointer size, so get it.
4785 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4786
4787 Offset &= PtrSizeMask;
4788 VariableScale &= PtrSizeMask;
4789
4790 // To do this transformation, any constant index must be a multiple of the
4791 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4792 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4793 // multiple of the variable scale.
4794 int64_t NewOffs = Offset / (int64_t)VariableScale;
4795 if (Offset != NewOffs*(int64_t)VariableScale)
4796 return 0;
4797
4798 // Okay, we can do this evaluation. Start by converting the index to intptr.
4799 const Type *IntPtrTy = TD.getIntPtrType();
4800 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004801 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004802 true /*SExt*/,
4803 VariableIdx->getNameStart(), &I);
4804 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004805 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004806}
4807
4808
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004810/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004811Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4812 ICmpInst::Predicate Cond,
4813 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004814 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004815
Chris Lattner10c0d912008-04-22 02:53:33 +00004816 // Look through bitcasts.
4817 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4818 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004819
Chris Lattner574da9b2005-01-13 20:14:25 +00004820 Value *PtrBase = GEPLHS->getOperand(0);
4821 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004822 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004823 // This transformation (ignoring the base and scales) is valid because we
4824 // know pointers can't overflow. See if we can output an optimized form.
4825 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4826
4827 // If not, synthesize the offset the hard way.
4828 if (Offset == 0)
4829 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004830 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4831 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004832 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004833 // If the base pointers are different, but the indices are the same, just
4834 // compare the base pointer.
4835 if (PtrBase != GEPRHS->getOperand(0)) {
4836 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004837 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004838 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004839 if (IndicesTheSame)
4840 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4841 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4842 IndicesTheSame = false;
4843 break;
4844 }
4845
4846 // If all indices are the same, just compare the base pointers.
4847 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004848 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4849 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004850
4851 // Otherwise, the base pointers are different and the indices are
4852 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004853 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004854 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004855
Chris Lattnere9d782b2005-01-13 22:25:21 +00004856 // If one of the GEPs has all zero indices, recurse.
4857 bool AllZeros = true;
4858 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4859 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4860 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4861 AllZeros = false;
4862 break;
4863 }
4864 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004865 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4866 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004867
4868 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004869 AllZeros = true;
4870 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4871 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4872 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4873 AllZeros = false;
4874 break;
4875 }
4876 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004878
Chris Lattner4401c9c2005-01-14 00:20:05 +00004879 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4880 // If the GEPs only differ by one index, compare it.
4881 unsigned NumDifferences = 0; // Keep track of # differences.
4882 unsigned DiffOperand = 0; // The operand that differs.
4883 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4884 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004885 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4886 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004887 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004888 NumDifferences = 2;
4889 break;
4890 } else {
4891 if (NumDifferences++) break;
4892 DiffOperand = i;
4893 }
4894 }
4895
4896 if (NumDifferences == 0) // SAME GEP?
4897 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004898 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004899 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004900
Chris Lattner4401c9c2005-01-14 00:20:05 +00004901 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004902 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4903 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004904 // Make sure we do a signed comparison here.
4905 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004906 }
4907 }
4908
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004910 // the result to fold to a constant!
4911 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4912 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4913 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4914 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4915 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004916 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004917 }
4918 }
4919 return 0;
4920}
4921
Chris Lattnera5406232008-05-19 20:18:56 +00004922/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4923///
4924Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4925 Instruction *LHSI,
4926 Constant *RHSC) {
4927 if (!isa<ConstantFP>(RHSC)) return 0;
4928 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4929
4930 // Get the width of the mantissa. We don't want to hack on conversions that
4931 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004932 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004933 if (MantissaWidth == -1) return 0; // Unknown.
4934
4935 // Check to see that the input is converted from an integer type that is small
4936 // enough that preserves all bits. TODO: check here for "known" sign bits.
4937 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4938 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4939
4940 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4941 if (isa<UIToFPInst>(LHSI))
4942 ++InputSize;
4943
4944 // If the conversion would lose info, don't hack on this.
4945 if ((int)InputSize > MantissaWidth)
4946 return 0;
4947
4948 // Otherwise, we can potentially simplify the comparison. We know that it
4949 // will always come through as an integer value and we know the constant is
4950 // not a NAN (it would have been previously simplified).
4951 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4952
4953 ICmpInst::Predicate Pred;
4954 switch (I.getPredicate()) {
4955 default: assert(0 && "Unexpected predicate!");
4956 case FCmpInst::FCMP_UEQ:
4957 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4958 case FCmpInst::FCMP_UGT:
4959 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4960 case FCmpInst::FCMP_UGE:
4961 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4962 case FCmpInst::FCMP_ULT:
4963 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4964 case FCmpInst::FCMP_ULE:
4965 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4966 case FCmpInst::FCMP_UNE:
4967 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4968 case FCmpInst::FCMP_ORD:
4969 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4970 case FCmpInst::FCMP_UNO:
4971 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4972 }
4973
4974 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4975
4976 // Now we know that the APFloat is a normal number, zero or inf.
4977
Chris Lattner85162782008-05-20 03:50:52 +00004978 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004979 // comparing an i8 to 300.0.
4980 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4981
4982 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4983 // and large values.
4984 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4985 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4986 APFloat::rmNearestTiesToEven);
4987 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004988 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4989 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004990 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4992 }
4993
4994 // See if the RHS value is < SignedMin.
4995 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4996 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4997 APFloat::rmNearestTiesToEven);
4998 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004999 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5000 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005001 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5002 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5003 }
5004
5005 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5006 // it may still be fractional. See if it is fractional by casting the FP
5007 // value to the integer value and back, checking for equality. Don't do this
5008 // for zero, because -0.0 is not fractional.
5009 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5010 if (!RHS.isZero() &&
5011 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5012 // If we had a comparison against a fractional value, we have to adjust
5013 // the compare predicate and sometimes the value. RHSC is rounded towards
5014 // zero at this point.
5015 switch (Pred) {
5016 default: assert(0 && "Unexpected integer comparison!");
5017 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5018 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5019 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5020 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5021 case ICmpInst::ICMP_SLE:
5022 // (float)int <= 4.4 --> int <= 4
5023 // (float)int <= -4.4 --> int < -4
5024 if (RHS.isNegative())
5025 Pred = ICmpInst::ICMP_SLT;
5026 break;
5027 case ICmpInst::ICMP_SLT:
5028 // (float)int < -4.4 --> int < -4
5029 // (float)int < 4.4 --> int <= 4
5030 if (!RHS.isNegative())
5031 Pred = ICmpInst::ICMP_SLE;
5032 break;
5033 case ICmpInst::ICMP_SGT:
5034 // (float)int > 4.4 --> int > 4
5035 // (float)int > -4.4 --> int >= -4
5036 if (RHS.isNegative())
5037 Pred = ICmpInst::ICMP_SGE;
5038 break;
5039 case ICmpInst::ICMP_SGE:
5040 // (float)int >= -4.4 --> int >= -4
5041 // (float)int >= 4.4 --> int > 4
5042 if (!RHS.isNegative())
5043 Pred = ICmpInst::ICMP_SGT;
5044 break;
5045 }
5046 }
5047
5048 // Lower this FP comparison into an appropriate integer version of the
5049 // comparison.
5050 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5051}
5052
Reid Spencere4d87aa2006-12-23 06:05:41 +00005053Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5054 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005055 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005056
Chris Lattner58e97462007-01-14 19:42:17 +00005057 // Fold trivial predicates.
5058 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5059 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5060 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5061 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5062
5063 // Simplify 'fcmp pred X, X'
5064 if (Op0 == Op1) {
5065 switch (I.getPredicate()) {
5066 default: assert(0 && "Unknown predicate!");
5067 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5068 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5069 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5070 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5071 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5072 case FCmpInst::FCMP_OLT: // True if ordered and less than
5073 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5074 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5075
5076 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5077 case FCmpInst::FCMP_ULT: // True if unordered or less than
5078 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5079 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5080 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5081 I.setPredicate(FCmpInst::FCMP_UNO);
5082 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5083 return &I;
5084
5085 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5086 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5087 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5088 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5089 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5090 I.setPredicate(FCmpInst::FCMP_ORD);
5091 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5092 return &I;
5093 }
5094 }
5095
Reid Spencere4d87aa2006-12-23 06:05:41 +00005096 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005097 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005098
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 // Handle fcmp with constant RHS
5100 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005101 // If the constant is a nan, see if we can fold the comparison based on it.
5102 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5103 if (CFP->getValueAPF().isNaN()) {
5104 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5105 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005106 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5107 "Comparison must be either ordered or unordered!");
5108 // True if unordered.
5109 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005110 }
5111 }
5112
Reid Spencere4d87aa2006-12-23 06:05:41 +00005113 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5114 switch (LHSI->getOpcode()) {
5115 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005116 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5117 // block. If in the same block, we're encouraging jump threading. If
5118 // not, we are just pessimizing the code by making an i1 phi.
5119 if (LHSI->getParent() == I.getParent())
5120 if (Instruction *NV = FoldOpIntoPhi(I))
5121 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005122 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005123 case Instruction::SIToFP:
5124 case Instruction::UIToFP:
5125 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5126 return NV;
5127 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005128 case Instruction::Select:
5129 // If either operand of the select is a constant, we can fold the
5130 // comparison into the select arms, which will cause one to be
5131 // constant folded and the select turned into a bitwise or.
5132 Value *Op1 = 0, *Op2 = 0;
5133 if (LHSI->hasOneUse()) {
5134 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5135 // Fold the known value into the constant operand.
5136 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5137 // Insert a new FCmp of the other select operand.
5138 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5139 LHSI->getOperand(2), RHSC,
5140 I.getName()), I);
5141 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5142 // Fold the known value into the constant operand.
5143 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5144 // Insert a new FCmp of the other select operand.
5145 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5146 LHSI->getOperand(1), RHSC,
5147 I.getName()), I);
5148 }
5149 }
5150
5151 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005152 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005153 break;
5154 }
5155 }
5156
5157 return Changed ? &I : 0;
5158}
5159
5160Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5161 bool Changed = SimplifyCompare(I);
5162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5163 const Type *Ty = Op0->getType();
5164
5165 // icmp X, X
5166 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005167 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005168 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169
5170 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005171 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005172
Reid Spencere4d87aa2006-12-23 06:05:41 +00005173 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005174 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005175 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5176 isa<ConstantPointerNull>(Op0)) &&
5177 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005178 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005179 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005180 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005181
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005183 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005184 switch (I.getPredicate()) {
5185 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005186 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005187 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005188 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005189 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005190 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005191 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005193
Reid Spencere4d87aa2006-12-23 06:05:41 +00005194 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005195 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005196 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005197 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005198 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005199 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005200 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005201 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005202 case ICmpInst::ICMP_SGT:
5203 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005204 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005205 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5206 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5207 InsertNewInstBefore(Not, I);
5208 return BinaryOperator::CreateAnd(Not, Op0);
5209 }
5210 case ICmpInst::ICMP_UGE:
5211 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5212 // FALL THROUGH
5213 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005214 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005215 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005216 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005217 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005218 case ICmpInst::ICMP_SGE:
5219 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5220 // FALL THROUGH
5221 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5222 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5223 InsertNewInstBefore(Not, I);
5224 return BinaryOperator::CreateOr(Not, Op0);
5225 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005226 }
Chris Lattner8b170942002-08-09 23:47:40 +00005227 }
5228
Chris Lattner2be51ae2004-06-09 04:24:29 +00005229 // See if we are doing a comparison between a constant and an instruction that
5230 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005231 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005232 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005233
Chris Lattnerb6566012008-01-05 01:18:20 +00005234 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5235 if (I.isEquality() && CI->isNullValue() &&
5236 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5237 // (icmp cond A B) if cond is equality
5238 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005239 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005240
Chris Lattner84dff672008-07-11 05:08:55 +00005241 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5242 // icmp lt or icmp gt instruction. This allows us to rely on them being
5243 // folded in the code below.
5244 switch (I.getPredicate()) {
5245 default: break;
5246 case ICmpInst::ICMP_ULE:
5247 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5248 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5249 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5250 case ICmpInst::ICMP_SLE:
5251 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5253 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5254 case ICmpInst::ICMP_UGE:
5255 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5256 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5257 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5258 case ICmpInst::ICMP_SGE:
5259 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5260 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5261 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5262 }
5263
Chris Lattner183661e2008-07-11 05:40:05 +00005264 // See if we can fold the comparison based on range information we can get
5265 // by checking whether bits are known to be zero or one in the input.
5266 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5267 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5268
5269 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005270 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005271 bool UnusedBit;
5272 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5273
Chris Lattner4241e4d2007-07-15 20:54:51 +00005274 if (SimplifyDemandedBits(Op0,
5275 isSignBit ? APInt::getSignBit(BitWidth)
5276 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005277 KnownZero, KnownOne, 0))
5278 return &I;
5279
5280 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005281 // in. Compute the Min, Max and RHS values based on the known bits. For the
5282 // EQ and NE we use unsigned values.
5283 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005284 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5285 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5286 else
5287 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5288
Chris Lattner183661e2008-07-11 05:40:05 +00005289 // If Min and Max are known to be the same, then SimplifyDemandedBits
5290 // figured out that the LHS is a constant. Just constant fold this now so
5291 // that code below can assume that Min != Max.
5292 if (Min == Max)
5293 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5294 ConstantInt::get(Min),
5295 CI));
5296
5297 // Based on the range information we know about the LHS, see if we can
5298 // simplify this comparison. For example, (x&4) < 8 is always true.
5299 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005300 switch (I.getPredicate()) { // LE/GE have been folded already.
5301 default: assert(0 && "Unknown icmp opcode!");
5302 case ICmpInst::ICMP_EQ:
5303 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5304 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5305 break;
5306 case ICmpInst::ICMP_NE:
5307 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5308 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5309 break;
5310 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005311 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005312 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005313 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005314 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005315 if (RHSVal == Max) // A <u MAX -> A != MAX
5316 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5317 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5318 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5319
5320 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5321 if (CI->isMinValue(true))
5322 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5323 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005324 break;
5325 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005326 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005327 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005328 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005329 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005330
5331 if (RHSVal == Min) // A >u MIN -> A != MIN
5332 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5333 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5334 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5335
5336 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5337 if (CI->isMaxValue(true))
5338 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5339 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005340 break;
5341 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005342 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005343 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005344 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005345 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005346 if (RHSVal == Max) // A <s MAX -> A != MAX
5347 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005348 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005349 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005350 break;
5351 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005352 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005353 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005354 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005355 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005356
5357 if (RHSVal == Min) // A >s MIN -> A != MIN
5358 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5359 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5360 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005361 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005362 }
5363
Reid Spencere4d87aa2006-12-23 06:05:41 +00005364 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005365 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005367 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005368 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5369 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005370 }
5371
Chris Lattner01deb9d2007-04-03 17:43:25 +00005372 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005373 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5374 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5375 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005376 case Instruction::GetElementPtr:
5377 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005378 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005379 bool isAllZeros = true;
5380 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5381 if (!isa<Constant>(LHSI->getOperand(i)) ||
5382 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5383 isAllZeros = false;
5384 break;
5385 }
5386 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005388 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5389 }
5390 break;
5391
Chris Lattner6970b662005-04-23 15:31:55 +00005392 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005393 // Only fold icmp into the PHI if the phi and fcmp are in the same
5394 // block. If in the same block, we're encouraging jump threading. If
5395 // not, we are just pessimizing the code by making an i1 phi.
5396 if (LHSI->getParent() == I.getParent())
5397 if (Instruction *NV = FoldOpIntoPhi(I))
5398 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005399 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005400 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005401 // If either operand of the select is a constant, we can fold the
5402 // comparison into the select arms, which will cause one to be
5403 // constant folded and the select turned into a bitwise or.
5404 Value *Op1 = 0, *Op2 = 0;
5405 if (LHSI->hasOneUse()) {
5406 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5407 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005408 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5409 // Insert a new ICmp of the other select operand.
5410 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5411 LHSI->getOperand(2), RHSC,
5412 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005413 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5414 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005415 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5416 // Insert a new ICmp of the other select operand.
5417 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5418 LHSI->getOperand(1), RHSC,
5419 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005420 }
5421 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005422
Chris Lattner6970b662005-04-23 15:31:55 +00005423 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005424 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005425 break;
5426 }
Chris Lattner4802d902007-04-06 18:57:34 +00005427 case Instruction::Malloc:
5428 // If we have (malloc != null), and if the malloc has a single use, we
5429 // can assume it is successful and remove the malloc.
5430 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5431 AddToWorkList(LHSI);
5432 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005433 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005434 }
5435 break;
5436 }
Chris Lattner6970b662005-04-23 15:31:55 +00005437 }
5438
Reid Spencere4d87aa2006-12-23 06:05:41 +00005439 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005440 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005441 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005442 return NI;
5443 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005444 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5445 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005446 return NI;
5447
Reid Spencere4d87aa2006-12-23 06:05:41 +00005448 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005449 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5450 // now.
5451 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5452 if (isa<PointerType>(Op0->getType()) &&
5453 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005454 // We keep moving the cast from the left operand over to the right
5455 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005456 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005457
Chris Lattner57d86372007-01-06 01:45:59 +00005458 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5459 // so eliminate it as well.
5460 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5461 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005462
Chris Lattnerde90b762003-11-03 04:25:02 +00005463 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005464 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005465 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005466 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005467 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005468 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005469 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005470 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005471 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005473 }
Chris Lattner57d86372007-01-06 01:45:59 +00005474 }
5475
5476 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005477 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005478 // This comes up when you have code like
5479 // int X = A < B;
5480 // if (X) ...
5481 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005482 // with a constant or another cast from the same type.
5483 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005484 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005485 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005486 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005487
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005488 // See if it's the same type of instruction on the left and right.
5489 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5490 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5491 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5492 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5493 I.isEquality()) {
5494 switch (Op0I->getOpcode()) {
5495 default: break;
5496 case Instruction::Add:
5497 case Instruction::Sub:
5498 case Instruction::Xor:
5499 // a+x icmp eq/ne b+x --> a icmp b
5500 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5501 Op1I->getOperand(0));
5502 break;
5503 case Instruction::Mul:
5504 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Nick Lewycky1f26c182008-07-11 07:36:19 +00005505 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
Nick Lewycky7d9843f2008-07-11 08:16:26 +00005506 // Mask = -1 >> count-trailing-zeros(Cst).
Nick Lewycky4bf1e592008-07-11 07:20:53 +00005507 if (!CI->isZero() && !CI->isOne()) {
5508 const APInt &AP = CI->getValue();
5509 ConstantInt *Mask = ConstantInt::get(
5510 APInt::getLowBitsSet(AP.getBitWidth(),
5511 AP.getBitWidth() -
5512 AP.countTrailingZeros()));
5513 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5514 Mask);
5515 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5516 Mask);
5517 InsertNewInstBefore(And1, I);
5518 InsertNewInstBefore(And2, I);
5519 return new ICmpInst(I.getPredicate(), And1, And2);
5520 }
5521 }
5522 break;
5523 }
5524 }
5525 }
5526 }
5527
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005528 // ~x < ~y --> y < x
5529 { Value *A, *B;
5530 if (match(Op0, m_Not(m_Value(A))) &&
5531 match(Op1, m_Not(m_Value(B))))
5532 return new ICmpInst(I.getPredicate(), B, A);
5533 }
5534
Chris Lattner65b72ba2006-09-18 04:22:48 +00005535 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005536 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005537
5538 // -x == -y --> x == y
5539 if (match(Op0, m_Neg(m_Value(A))) &&
5540 match(Op1, m_Neg(m_Value(B))))
5541 return new ICmpInst(I.getPredicate(), A, B);
5542
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005543 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5544 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5545 Value *OtherVal = A == Op1 ? B : A;
5546 return new ICmpInst(I.getPredicate(), OtherVal,
5547 Constant::getNullValue(A->getType()));
5548 }
5549
5550 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5551 // A^c1 == C^c2 --> A == C^(c1^c2)
5552 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5553 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5554 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005555 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005556 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005557 return new ICmpInst(I.getPredicate(), A,
5558 InsertNewInstBefore(Xor, I));
5559 }
5560
5561 // A^B == A^D -> B == D
5562 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5563 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5564 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5565 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5566 }
5567 }
5568
5569 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5570 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005571 // A == (A^B) -> B == 0
5572 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005573 return new ICmpInst(I.getPredicate(), OtherVal,
5574 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005575 }
5576 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005577 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005578 return new ICmpInst(I.getPredicate(), B,
5579 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005580 }
5581 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005582 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 return new ICmpInst(I.getPredicate(), B,
5584 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005585 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005586
Chris Lattner9c2328e2006-11-14 06:06:06 +00005587 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5588 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5589 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5590 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5591 Value *X = 0, *Y = 0, *Z = 0;
5592
5593 if (A == C) {
5594 X = B; Y = D; Z = A;
5595 } else if (A == D) {
5596 X = B; Y = C; Z = A;
5597 } else if (B == C) {
5598 X = A; Y = D; Z = B;
5599 } else if (B == D) {
5600 X = A; Y = C; Z = B;
5601 }
5602
5603 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005604 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5605 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005606 I.setOperand(0, Op1);
5607 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5608 return &I;
5609 }
5610 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005611 }
Chris Lattner7e708292002-06-25 16:13:24 +00005612 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005613}
5614
Chris Lattner562ef782007-06-20 23:46:26 +00005615
5616/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5617/// and CmpRHS are both known to be integer constants.
5618Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5619 ConstantInt *DivRHS) {
5620 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5621 const APInt &CmpRHSV = CmpRHS->getValue();
5622
5623 // FIXME: If the operand types don't match the type of the divide
5624 // then don't attempt this transform. The code below doesn't have the
5625 // logic to deal with a signed divide and an unsigned compare (and
5626 // vice versa). This is because (x /s C1) <s C2 produces different
5627 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5628 // (x /u C1) <u C2. Simply casting the operands and result won't
5629 // work. :( The if statement below tests that condition and bails
5630 // if it finds it.
5631 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5632 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5633 return 0;
5634 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005635 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005636
5637 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5638 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5639 // C2 (CI). By solving for X we can turn this into a range check
5640 // instead of computing a divide.
5641 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5642
5643 // Determine if the product overflows by seeing if the product is
5644 // not equal to the divide. Make sure we do the same kind of divide
5645 // as in the LHS instruction that we're folding.
5646 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5647 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5648
5649 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005650 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005651
Chris Lattner1dbfd482007-06-21 18:11:19 +00005652 // Figure out the interval that is being checked. For example, a comparison
5653 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5654 // Compute this interval based on the constants involved and the signedness of
5655 // the compare/divide. This computes a half-open interval, keeping track of
5656 // whether either value in the interval overflows. After analysis each
5657 // overflow variable is set to 0 if it's corresponding bound variable is valid
5658 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5659 int LoOverflow = 0, HiOverflow = 0;
5660 ConstantInt *LoBound = 0, *HiBound = 0;
5661
5662
Chris Lattner562ef782007-06-20 23:46:26 +00005663 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005664 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005665 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005666 HiOverflow = LoOverflow = ProdOV;
5667 if (!HiOverflow)
5668 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005669 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005670 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005671 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005672 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5673 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005674 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005675 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5676 HiOverflow = LoOverflow = ProdOV;
5677 if (!HiOverflow)
5678 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005679 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005680 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005681 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5682 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005683 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005684 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005685 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005686 }
Dan Gohman76491272008-02-13 22:09:18 +00005687 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005688 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005689 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005690 LoBound = AddOne(DivRHS);
5691 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005692 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5693 HiOverflow = 1; // [INTMIN+1, overflow)
5694 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5695 }
Dan Gohman76491272008-02-13 22:09:18 +00005696 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005697 // e.g. X/-5 op 3 --> [-19, -14)
5698 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005699 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005700 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005701 HiBound = AddOne(Prod);
5702 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005703 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005704 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005705 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005706 HiBound = Subtract(Prod, DivRHS);
5707 }
5708
Chris Lattner1dbfd482007-06-21 18:11:19 +00005709 // Dividing by a negative swaps the condition. LT <-> GT
5710 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005711 }
5712
5713 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005714 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005715 default: assert(0 && "Unhandled icmp opcode!");
5716 case ICmpInst::ICMP_EQ:
5717 if (LoOverflow && HiOverflow)
5718 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5719 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005720 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005721 ICmpInst::ICMP_UGE, X, LoBound);
5722 else if (LoOverflow)
5723 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5724 ICmpInst::ICMP_ULT, X, HiBound);
5725 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005726 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005727 case ICmpInst::ICMP_NE:
5728 if (LoOverflow && HiOverflow)
5729 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5730 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005731 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005732 ICmpInst::ICMP_ULT, X, LoBound);
5733 else if (LoOverflow)
5734 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5735 ICmpInst::ICMP_UGE, X, HiBound);
5736 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005737 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005738 case ICmpInst::ICMP_ULT:
5739 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005740 if (LoOverflow == +1) // Low bound is greater than input range.
5741 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5742 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005743 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005744 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005745 case ICmpInst::ICMP_UGT:
5746 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005747 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005748 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005749 else if (HiOverflow == -1) // High bound less than input range.
5750 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5751 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005752 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5753 else
5754 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5755 }
5756}
5757
5758
Chris Lattner01deb9d2007-04-03 17:43:25 +00005759/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5760///
5761Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5762 Instruction *LHSI,
5763 ConstantInt *RHS) {
5764 const APInt &RHSV = RHS->getValue();
5765
5766 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005767 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005768 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5769 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5770 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005771 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5772 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005773 Value *CompareVal = LHSI->getOperand(0);
5774
5775 // If the sign bit of the XorCST is not set, there is no change to
5776 // the operation, just stop using the Xor.
5777 if (!XorCST->getValue().isNegative()) {
5778 ICI.setOperand(0, CompareVal);
5779 AddToWorkList(LHSI);
5780 return &ICI;
5781 }
5782
5783 // Was the old condition true if the operand is positive?
5784 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5785
5786 // If so, the new one isn't.
5787 isTrueIfPositive ^= true;
5788
5789 if (isTrueIfPositive)
5790 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5791 else
5792 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5793 }
5794 }
5795 break;
5796 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5797 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5798 LHSI->getOperand(0)->hasOneUse()) {
5799 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5800
5801 // If the LHS is an AND of a truncating cast, we can widen the
5802 // and/compare to be the input width without changing the value
5803 // produced, eliminating a cast.
5804 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5805 // We can do this transformation if either the AND constant does not
5806 // have its sign bit set or if it is an equality comparison.
5807 // Extending a relational comparison when we're checking the sign
5808 // bit would not work.
5809 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005810 (ICI.isEquality() ||
5811 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005812 uint32_t BitWidth =
5813 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5814 APInt NewCST = AndCST->getValue();
5815 NewCST.zext(BitWidth);
5816 APInt NewCI = RHSV;
5817 NewCI.zext(BitWidth);
5818 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005819 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005820 ConstantInt::get(NewCST),LHSI->getName());
5821 InsertNewInstBefore(NewAnd, ICI);
5822 return new ICmpInst(ICI.getPredicate(), NewAnd,
5823 ConstantInt::get(NewCI));
5824 }
5825 }
5826
5827 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5828 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5829 // happens a LOT in code produced by the C front-end, for bitfield
5830 // access.
5831 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5832 if (Shift && !Shift->isShift())
5833 Shift = 0;
5834
5835 ConstantInt *ShAmt;
5836 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5837 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5838 const Type *AndTy = AndCST->getType(); // Type of the and.
5839
5840 // We can fold this as long as we can't shift unknown bits
5841 // into the mask. This can only happen with signed shift
5842 // rights, as they sign-extend.
5843 if (ShAmt) {
5844 bool CanFold = Shift->isLogicalShift();
5845 if (!CanFold) {
5846 // To test for the bad case of the signed shr, see if any
5847 // of the bits shifted in could be tested after the mask.
5848 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5849 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5850
5851 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5852 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5853 AndCST->getValue()) == 0)
5854 CanFold = true;
5855 }
5856
5857 if (CanFold) {
5858 Constant *NewCst;
5859 if (Shift->getOpcode() == Instruction::Shl)
5860 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5861 else
5862 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5863
5864 // Check to see if we are shifting out any of the bits being
5865 // compared.
5866 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5867 // If we shifted bits out, the fold is not going to work out.
5868 // As a special case, check to see if this means that the
5869 // result is always true or false now.
5870 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5871 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5872 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5874 } else {
5875 ICI.setOperand(1, NewCst);
5876 Constant *NewAndCST;
5877 if (Shift->getOpcode() == Instruction::Shl)
5878 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5879 else
5880 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5881 LHSI->setOperand(1, NewAndCST);
5882 LHSI->setOperand(0, Shift->getOperand(0));
5883 AddToWorkList(Shift); // Shift is dead.
5884 AddUsesToWorkList(ICI);
5885 return &ICI;
5886 }
5887 }
5888 }
5889
5890 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5891 // preferable because it allows the C<<Y expression to be hoisted out
5892 // of a loop if Y is invariant and X is not.
5893 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5894 ICI.isEquality() && !Shift->isArithmeticShift() &&
5895 isa<Instruction>(Shift->getOperand(0))) {
5896 // Compute C << Y.
5897 Value *NS;
5898 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005899 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005900 Shift->getOperand(1), "tmp");
5901 } else {
5902 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005903 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005904 Shift->getOperand(1), "tmp");
5905 }
5906 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5907
5908 // Compute X & (C << Y).
5909 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005910 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005911 InsertNewInstBefore(NewAnd, ICI);
5912
5913 ICI.setOperand(0, NewAnd);
5914 return &ICI;
5915 }
5916 }
5917 break;
5918
Chris Lattnera0141b92007-07-15 20:42:37 +00005919 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5920 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5921 if (!ShAmt) break;
5922
5923 uint32_t TypeBits = RHSV.getBitWidth();
5924
5925 // Check that the shift amount is in range. If not, don't perform
5926 // undefined shifts. When the shift is visited it will be
5927 // simplified.
5928 if (ShAmt->uge(TypeBits))
5929 break;
5930
5931 if (ICI.isEquality()) {
5932 // If we are comparing against bits always shifted out, the
5933 // comparison cannot succeed.
5934 Constant *Comp =
5935 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5936 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5937 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5938 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5939 return ReplaceInstUsesWith(ICI, Cst);
5940 }
5941
5942 if (LHSI->hasOneUse()) {
5943 // Otherwise strength reduce the shift into an and.
5944 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5945 Constant *Mask =
5946 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005947
Chris Lattnera0141b92007-07-15 20:42:37 +00005948 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005949 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005950 Mask, LHSI->getName()+".mask");
5951 Value *And = InsertNewInstBefore(AndI, ICI);
5952 return new ICmpInst(ICI.getPredicate(), And,
5953 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005954 }
5955 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005956
5957 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5958 bool TrueIfSigned = false;
5959 if (LHSI->hasOneUse() &&
5960 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5961 // (X << 31) <s 0 --> (X&1) != 0
5962 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5963 (TypeBits-ShAmt->getZExtValue()-1));
5964 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005965 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005966 Mask, LHSI->getName()+".mask");
5967 Value *And = InsertNewInstBefore(AndI, ICI);
5968
5969 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5970 And, Constant::getNullValue(And->getType()));
5971 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005972 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005973 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005974
5975 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005976 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005977 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005978 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005979 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005980
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005981 // Check that the shift amount is in range. If not, don't perform
5982 // undefined shifts. When the shift is visited it will be
5983 // simplified.
5984 uint32_t TypeBits = RHSV.getBitWidth();
5985 if (ShAmt->uge(TypeBits))
5986 break;
5987
5988 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005989
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005990 // If we are comparing against bits always shifted out, the
5991 // comparison cannot succeed.
5992 APInt Comp = RHSV << ShAmtVal;
5993 if (LHSI->getOpcode() == Instruction::LShr)
5994 Comp = Comp.lshr(ShAmtVal);
5995 else
5996 Comp = Comp.ashr(ShAmtVal);
5997
5998 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5999 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6000 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6001 return ReplaceInstUsesWith(ICI, Cst);
6002 }
6003
6004 // Otherwise, check to see if the bits shifted out are known to be zero.
6005 // If so, we can compare against the unshifted value:
6006 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006007 if (LHSI->hasOneUse() &&
6008 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006009 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6010 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6011 ConstantExpr::getShl(RHS, ShAmt));
6012 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006013
Evan Chengf30752c2008-04-23 00:38:06 +00006014 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006015 // Otherwise strength reduce the shift into an and.
6016 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6017 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006018
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006019 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006020 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006021 Mask, LHSI->getName()+".mask");
6022 Value *And = InsertNewInstBefore(AndI, ICI);
6023 return new ICmpInst(ICI.getPredicate(), And,
6024 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006025 }
6026 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006027 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006028
6029 case Instruction::SDiv:
6030 case Instruction::UDiv:
6031 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6032 // Fold this div into the comparison, producing a range check.
6033 // Determine, based on the divide type, what the range is being
6034 // checked. If there is an overflow on the low or high side, remember
6035 // it, otherwise compute the range [low, hi) bounding the new value.
6036 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006037 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6038 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6039 DivRHS))
6040 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006041 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006042
6043 case Instruction::Add:
6044 // Fold: icmp pred (add, X, C1), C2
6045
6046 if (!ICI.isEquality()) {
6047 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6048 if (!LHSC) break;
6049 const APInt &LHSV = LHSC->getValue();
6050
6051 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6052 .subtract(LHSV);
6053
6054 if (ICI.isSignedPredicate()) {
6055 if (CR.getLower().isSignBit()) {
6056 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6057 ConstantInt::get(CR.getUpper()));
6058 } else if (CR.getUpper().isSignBit()) {
6059 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6060 ConstantInt::get(CR.getLower()));
6061 }
6062 } else {
6063 if (CR.getLower().isMinValue()) {
6064 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6065 ConstantInt::get(CR.getUpper()));
6066 } else if (CR.getUpper().isMinValue()) {
6067 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6068 ConstantInt::get(CR.getLower()));
6069 }
6070 }
6071 }
6072 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006073 }
6074
6075 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6076 if (ICI.isEquality()) {
6077 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6078
6079 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6080 // the second operand is a constant, simplify a bit.
6081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6082 switch (BO->getOpcode()) {
6083 case Instruction::SRem:
6084 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6085 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6086 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6087 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6088 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006089 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006090 BO->getName());
6091 InsertNewInstBefore(NewRem, ICI);
6092 return new ICmpInst(ICI.getPredicate(), NewRem,
6093 Constant::getNullValue(BO->getType()));
6094 }
6095 }
6096 break;
6097 case Instruction::Add:
6098 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6099 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6100 if (BO->hasOneUse())
6101 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6102 Subtract(RHS, BOp1C));
6103 } else if (RHSV == 0) {
6104 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6105 // efficiently invertible, or if the add has just this one use.
6106 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6107
6108 if (Value *NegVal = dyn_castNegVal(BOp1))
6109 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6110 else if (Value *NegVal = dyn_castNegVal(BOp0))
6111 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6112 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006113 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006114 InsertNewInstBefore(Neg, ICI);
6115 Neg->takeName(BO);
6116 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6117 }
6118 }
6119 break;
6120 case Instruction::Xor:
6121 // For the xor case, we can xor two constants together, eliminating
6122 // the explicit xor.
6123 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6124 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6125 ConstantExpr::getXor(RHS, BOC));
6126
6127 // FALLTHROUGH
6128 case Instruction::Sub:
6129 // Replace (([sub|xor] A, B) != 0) with (A != B)
6130 if (RHSV == 0)
6131 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6132 BO->getOperand(1));
6133 break;
6134
6135 case Instruction::Or:
6136 // If bits are being or'd in that are not present in the constant we
6137 // are comparing against, then the comparison could never succeed!
6138 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6139 Constant *NotCI = ConstantExpr::getNot(RHS);
6140 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6141 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6142 isICMP_NE));
6143 }
6144 break;
6145
6146 case Instruction::And:
6147 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6148 // If bits are being compared against that are and'd out, then the
6149 // comparison can never succeed!
6150 if ((RHSV & ~BOC->getValue()) != 0)
6151 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6152 isICMP_NE));
6153
6154 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6155 if (RHS == BOC && RHSV.isPowerOf2())
6156 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6157 ICmpInst::ICMP_NE, LHSI,
6158 Constant::getNullValue(RHS->getType()));
6159
6160 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006161 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006162 Value *X = BO->getOperand(0);
6163 Constant *Zero = Constant::getNullValue(X->getType());
6164 ICmpInst::Predicate pred = isICMP_NE ?
6165 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6166 return new ICmpInst(pred, X, Zero);
6167 }
6168
6169 // ((X & ~7) == 0) --> X < 8
6170 if (RHSV == 0 && isHighOnes(BOC)) {
6171 Value *X = BO->getOperand(0);
6172 Constant *NegX = ConstantExpr::getNeg(BOC);
6173 ICmpInst::Predicate pred = isICMP_NE ?
6174 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6175 return new ICmpInst(pred, X, NegX);
6176 }
6177 }
6178 default: break;
6179 }
6180 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6181 // Handle icmp {eq|ne} <intrinsic>, intcst.
6182 if (II->getIntrinsicID() == Intrinsic::bswap) {
6183 AddToWorkList(II);
6184 ICI.setOperand(0, II->getOperand(1));
6185 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6186 return &ICI;
6187 }
6188 }
6189 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006190 // If the LHS is a cast from an integral value of the same size,
6191 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006192 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6193 Value *CastOp = Cast->getOperand(0);
6194 const Type *SrcTy = CastOp->getType();
6195 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6196 if (SrcTy->isInteger() &&
6197 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6198 // If this is an unsigned comparison, try to make the comparison use
6199 // smaller constant values.
6200 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6201 // X u< 128 => X s> -1
6202 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6203 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6204 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6205 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6206 // X u> 127 => X s< 0
6207 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6208 Constant::getNullValue(SrcTy));
6209 }
6210 }
6211 }
6212 }
6213 return 0;
6214}
6215
6216/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6217/// We only handle extending casts so far.
6218///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006219Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6220 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006221 Value *LHSCIOp = LHSCI->getOperand(0);
6222 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006223 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006224 Value *RHSCIOp;
6225
Chris Lattner8c756c12007-05-05 22:41:33 +00006226 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6227 // integer type is the same size as the pointer type.
6228 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6229 getTargetData().getPointerSizeInBits() ==
6230 cast<IntegerType>(DestTy)->getBitWidth()) {
6231 Value *RHSOp = 0;
6232 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006233 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006234 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6235 RHSOp = RHSC->getOperand(0);
6236 // If the pointer types don't match, insert a bitcast.
6237 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006238 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006239 }
6240
6241 if (RHSOp)
6242 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6243 }
6244
6245 // The code below only handles extension cast instructions, so far.
6246 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006247 if (LHSCI->getOpcode() != Instruction::ZExt &&
6248 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006249 return 0;
6250
Reid Spencere4d87aa2006-12-23 06:05:41 +00006251 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6252 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006253
Reid Spencere4d87aa2006-12-23 06:05:41 +00006254 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006255 // Not an extension from the same type?
6256 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006257 if (RHSCIOp->getType() != LHSCIOp->getType())
6258 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006259
Nick Lewycky4189a532008-01-28 03:48:02 +00006260 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006261 // and the other is a zext), then we can't handle this.
6262 if (CI->getOpcode() != LHSCI->getOpcode())
6263 return 0;
6264
Nick Lewycky4189a532008-01-28 03:48:02 +00006265 // Deal with equality cases early.
6266 if (ICI.isEquality())
6267 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6268
6269 // A signed comparison of sign extended values simplifies into a
6270 // signed comparison.
6271 if (isSignedCmp && isSignedExt)
6272 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6273
6274 // The other three cases all fold into an unsigned comparison.
6275 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006276 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006277
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // If we aren't dealing with a constant on the RHS, exit early
6279 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6280 if (!CI)
6281 return 0;
6282
6283 // Compute the constant that would happen if we truncated to SrcTy then
6284 // reextended to DestTy.
6285 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6286 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6287
6288 // If the re-extended constant didn't change...
6289 if (Res2 == CI) {
6290 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6291 // For example, we might have:
6292 // %A = sext short %X to uint
6293 // %B = icmp ugt uint %A, 1330
6294 // It is incorrect to transform this into
6295 // %B = icmp ugt short %X, 1330
6296 // because %A may have negative value.
6297 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006298 // However, we allow this when the compare is EQ/NE, because they are
6299 // signless.
6300 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006302 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 }
6304
6305 // The re-extended constant changed so the constant cannot be represented
6306 // in the shorter type. Consequently, we cannot emit a simple comparison.
6307
6308 // First, handle some easy cases. We know the result cannot be equal at this
6309 // point so handle the ICI.isEquality() cases
6310 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006311 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006312 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006313 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006314
6315 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6316 // should have been folded away previously and not enter in here.
6317 Value *Result;
6318 if (isSignedCmp) {
6319 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006320 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006321 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006322 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006323 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 } else {
6325 // We're performing an unsigned comparison.
6326 if (isSignedExt) {
6327 // We're performing an unsigned comp with a sign extended value.
6328 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006329 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6331 NegOne, ICI.getName()), ICI);
6332 } else {
6333 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006334 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 }
6336 }
6337
6338 // Finally, return the value computed.
6339 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006340 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006342
6343 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6344 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6345 "ICmp should be folded!");
6346 if (Constant *CI = dyn_cast<Constant>(Result))
6347 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6348 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006349}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006350
Reid Spencer832254e2007-02-02 02:16:23 +00006351Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6352 return commonShiftTransforms(I);
6353}
6354
6355Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6356 return commonShiftTransforms(I);
6357}
6358
6359Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006360 if (Instruction *R = commonShiftTransforms(I))
6361 return R;
6362
6363 Value *Op0 = I.getOperand(0);
6364
6365 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6366 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6367 if (CSI->isAllOnesValue())
6368 return ReplaceInstUsesWith(I, CSI);
6369
6370 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006371 if (!isa<VectorType>(I.getType()) &&
6372 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006373 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006374 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006375
6376 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006377}
6378
6379Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6380 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006382
6383 // shl X, 0 == X and shr X, 0 == X
6384 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006385 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006386 Op0 == Constant::getNullValue(Op0->getType()))
6387 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006388
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 if (isa<UndefValue>(Op0)) {
6390 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006391 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006392 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006393 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6394 }
6395 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6397 return ReplaceInstUsesWith(I, Op0);
6398 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006399 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006400 }
6401
Chris Lattner2eefe512004-04-09 19:05:30 +00006402 // Try to fold constant and into select arguments.
6403 if (isa<Constant>(Op0))
6404 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006405 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006406 return R;
6407
Reid Spencerb83eb642006-10-20 07:07:24 +00006408 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006409 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6410 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006411 return 0;
6412}
6413
Reid Spencerb83eb642006-10-20 07:07:24 +00006414Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006415 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006416 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006417
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006418 // See if we can simplify any instructions used by the instruction whose sole
6419 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006420 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6421 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6422 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006423 KnownZero, KnownOne))
6424 return &I;
6425
Chris Lattner4d5542c2006-01-06 07:12:35 +00006426 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6427 // of a signed value.
6428 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006429 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006430 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006431 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6432 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006433 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006434 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006435 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006436 }
6437
6438 // ((X*C1) << C2) == (X * (C1 << C2))
6439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6440 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6441 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006442 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006443 ConstantExpr::getShl(BOOp, Op1));
6444
6445 // Try to fold constant and into select arguments.
6446 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6447 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6448 return R;
6449 if (isa<PHINode>(Op0))
6450 if (Instruction *NV = FoldOpIntoPhi(I))
6451 return NV;
6452
Chris Lattner8999dd32007-12-22 09:07:47 +00006453 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6454 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6455 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6456 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6457 // place. Don't try to do this transformation in this case. Also, we
6458 // require that the input operand is a shift-by-constant so that we have
6459 // confidence that the shifts will get folded together. We could do this
6460 // xform in more cases, but it is unlikely to be profitable.
6461 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6462 isa<ConstantInt>(TrOp->getOperand(1))) {
6463 // Okay, we'll do this xform. Make the shift of shift.
6464 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006465 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006466 I.getName());
6467 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6468
6469 // For logical shifts, the truncation has the effect of making the high
6470 // part of the register be zeros. Emulate this by inserting an AND to
6471 // clear the top bits as needed. This 'and' will usually be zapped by
6472 // other xforms later if dead.
6473 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6474 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6475 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6476
6477 // The mask we constructed says what the trunc would do if occurring
6478 // between the shifts. We want to know the effect *after* the second
6479 // shift. We know that it is a logical shift by a constant, so adjust the
6480 // mask as appropriate.
6481 if (I.getOpcode() == Instruction::Shl)
6482 MaskV <<= Op1->getZExtValue();
6483 else {
6484 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6485 MaskV = MaskV.lshr(Op1->getZExtValue());
6486 }
6487
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006488 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006489 TI->getName());
6490 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6491
6492 // Return the value truncated to the interesting size.
6493 return new TruncInst(And, I.getType());
6494 }
6495 }
6496
Chris Lattner4d5542c2006-01-06 07:12:35 +00006497 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006498 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6499 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6500 Value *V1, *V2;
6501 ConstantInt *CC;
6502 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006503 default: break;
6504 case Instruction::Add:
6505 case Instruction::And:
6506 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006507 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006508 // These operators commute.
6509 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006510 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6511 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006512 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006513 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006514 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006515 Op0BO->getName());
6516 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006517 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006518 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006519 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006520 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006521 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006522 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006523 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006524 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006525
Chris Lattner150f12a2005-09-18 06:30:59 +00006526 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006527 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006528 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006529 match(Op0BOOp1,
6530 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006531 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6532 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006533 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006534 Op0BO->getOperand(0), Op1,
6535 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006536 InsertNewInstBefore(YS, I); // (Y << C)
6537 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006539 V1->getName()+".mask");
6540 InsertNewInstBefore(XM, I); // X & (CC << C)
6541
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006542 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006543 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006544 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006545
Reid Spencera07cb7d2007-02-02 14:41:37 +00006546 // FALL THROUGH.
6547 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006548 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006549 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6550 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006551 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006552 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006553 Op0BO->getOperand(1), Op1,
6554 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006555 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006556 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006557 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006558 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006559 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006560 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006561 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006562 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006563 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006564
Chris Lattner13d4ab42006-05-31 21:14:00 +00006565 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006566 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6567 match(Op0BO->getOperand(0),
6568 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006569 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006570 cast<BinaryOperator>(Op0BO->getOperand(0))
6571 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006572 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006573 Op0BO->getOperand(1), Op1,
6574 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006575 InsertNewInstBefore(YS, I); // (Y << C)
6576 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006577 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006578 V1->getName()+".mask");
6579 InsertNewInstBefore(XM, I); // X & (CC << C)
6580
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006581 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006582 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006583
Chris Lattner11021cb2005-09-18 05:12:10 +00006584 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006585 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006586 }
6587
6588
6589 // If the operand is an bitwise operator with a constant RHS, and the
6590 // shift is the only use, we can pull it out of the shift.
6591 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6592 bool isValid = true; // Valid only for And, Or, Xor
6593 bool highBitSet = false; // Transform if high bit of constant set?
6594
6595 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006596 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006597 case Instruction::Add:
6598 isValid = isLeftShift;
6599 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006600 case Instruction::Or:
6601 case Instruction::Xor:
6602 highBitSet = false;
6603 break;
6604 case Instruction::And:
6605 highBitSet = true;
6606 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006607 }
6608
6609 // If this is a signed shift right, and the high bit is modified
6610 // by the logical operation, do not perform the transformation.
6611 // The highBitSet boolean indicates the value of the high bit of
6612 // the constant which would cause it to be modified for this
6613 // operation.
6614 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006615 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006616 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006617
6618 if (isValid) {
6619 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6620
6621 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006622 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006623 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006624 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006625
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006626 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006627 NewRHS);
6628 }
6629 }
6630 }
6631 }
6632
Chris Lattnerad0124c2006-01-06 07:52:12 +00006633 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006634 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6635 if (ShiftOp && !ShiftOp->isShift())
6636 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006637
Reid Spencerb83eb642006-10-20 07:07:24 +00006638 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006639 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006640 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6641 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006642 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6643 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6644 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006645
Zhou Sheng4351c642007-04-02 08:20:41 +00006646 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006647 if (AmtSum > TypeBits)
6648 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006649
6650 const IntegerType *Ty = cast<IntegerType>(I.getType());
6651
6652 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006653 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006654 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006655 ConstantInt::get(Ty, AmtSum));
6656 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6657 I.getOpcode() == Instruction::AShr) {
6658 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006659 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006660 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6661 I.getOpcode() == Instruction::LShr) {
6662 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6663 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006664 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006665 InsertNewInstBefore(Shift, I);
6666
Zhou Shenge9e03f62007-03-28 15:02:20 +00006667 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006668 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006669 }
6670
Chris Lattnerb87056f2007-02-05 00:57:54 +00006671 // Okay, if we get here, one shift must be left, and the other shift must be
6672 // right. See if the amounts are equal.
6673 if (ShiftAmt1 == ShiftAmt2) {
6674 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6675 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006676 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006677 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006678 }
6679 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6680 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006681 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006682 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006683 }
6684 // We can simplify ((X << C) >>s C) into a trunc + sext.
6685 // NOTE: we could do this for any C, but that would make 'unusual' integer
6686 // types. For now, just stick to ones well-supported by the code
6687 // generators.
6688 const Type *SExtType = 0;
6689 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006690 case 1 :
6691 case 8 :
6692 case 16 :
6693 case 32 :
6694 case 64 :
6695 case 128:
6696 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6697 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006698 default: break;
6699 }
6700 if (SExtType) {
6701 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6702 InsertNewInstBefore(NewTrunc, I);
6703 return new SExtInst(NewTrunc, Ty);
6704 }
6705 // Otherwise, we can't handle it yet.
6706 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006707 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006708
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006709 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006710 if (I.getOpcode() == Instruction::Shl) {
6711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6712 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006713 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006714 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006715 InsertNewInstBefore(Shift, I);
6716
Reid Spencer55702aa2007-03-25 21:11:44 +00006717 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006718 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006719 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006720
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006721 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006722 if (I.getOpcode() == Instruction::LShr) {
6723 assert(ShiftOp->getOpcode() == Instruction::Shl);
6724 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006725 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006726 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006727
Reid Spencerd5e30f02007-03-26 17:18:58 +00006728 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006729 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006730 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006731
6732 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6733 } else {
6734 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006735 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006736
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006737 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006738 if (I.getOpcode() == Instruction::Shl) {
6739 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6740 ShiftOp->getOpcode() == Instruction::AShr);
6741 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006742 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006743 ConstantInt::get(Ty, ShiftDiff));
6744 InsertNewInstBefore(Shift, I);
6745
Reid Spencer55702aa2007-03-25 21:11:44 +00006746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006747 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006748 }
6749
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006750 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006751 if (I.getOpcode() == Instruction::LShr) {
6752 assert(ShiftOp->getOpcode() == Instruction::Shl);
6753 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006754 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006755 InsertNewInstBefore(Shift, I);
6756
Reid Spencer68d27cf2007-03-26 23:45:51 +00006757 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006758 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006759 }
6760
6761 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006762 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006763 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006764 return 0;
6765}
6766
Chris Lattnera1be5662002-05-02 17:06:02 +00006767
Chris Lattnercfd65102005-10-29 04:36:15 +00006768/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6769/// expression. If so, decompose it, returning some value X, such that Val is
6770/// X*Scale+Offset.
6771///
6772static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006773 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006774 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006775 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006776 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006777 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006778 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006779 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6780 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6781 if (I->getOpcode() == Instruction::Shl) {
6782 // This is a value scaled by '1 << the shift amt'.
6783 Scale = 1U << RHS->getZExtValue();
6784 Offset = 0;
6785 return I->getOperand(0);
6786 } else if (I->getOpcode() == Instruction::Mul) {
6787 // This value is scaled by 'RHS'.
6788 Scale = RHS->getZExtValue();
6789 Offset = 0;
6790 return I->getOperand(0);
6791 } else if (I->getOpcode() == Instruction::Add) {
6792 // We have X+C. Check to see if we really have (X*C2)+C1,
6793 // where C1 is divisible by C2.
6794 unsigned SubScale;
6795 Value *SubVal =
6796 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6797 Offset += RHS->getZExtValue();
6798 Scale = SubScale;
6799 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006800 }
6801 }
6802 }
6803
6804 // Otherwise, we can't look past this.
6805 Scale = 1;
6806 Offset = 0;
6807 return Val;
6808}
6809
6810
Chris Lattnerb3f83972005-10-24 06:03:58 +00006811/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6812/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006813Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006814 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006815 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006816
Chris Lattnerb53c2382005-10-24 06:22:12 +00006817 // Remove any uses of AI that are dead.
6818 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006819
Chris Lattnerb53c2382005-10-24 06:22:12 +00006820 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6821 Instruction *User = cast<Instruction>(*UI++);
6822 if (isInstructionTriviallyDead(User)) {
6823 while (UI != E && *UI == User)
6824 ++UI; // If this instruction uses AI more than once, don't break UI.
6825
Chris Lattnerb53c2382005-10-24 06:22:12 +00006826 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006827 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006828 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006829 }
6830 }
6831
Chris Lattnerb3f83972005-10-24 06:03:58 +00006832 // Get the type really allocated and the type casted to.
6833 const Type *AllocElTy = AI.getAllocatedType();
6834 const Type *CastElTy = PTy->getElementType();
6835 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006836
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006837 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6838 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006839 if (CastElTyAlign < AllocElTyAlign) return 0;
6840
Chris Lattner39387a52005-10-24 06:35:18 +00006841 // If the allocation has multiple uses, only promote it if we are strictly
6842 // increasing the alignment of the resultant allocation. If we keep it the
6843 // same, we open the door to infinite loops of various kinds.
6844 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6845
Duncan Sands514ab342007-11-01 20:53:16 +00006846 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6847 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006848 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006849
Chris Lattner455fcc82005-10-29 03:19:53 +00006850 // See if we can satisfy the modulus by pulling a scale out of the array
6851 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006852 unsigned ArraySizeScale;
6853 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006854 Value *NumElements = // See if the array size is a decomposable linear expr.
6855 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6856
Chris Lattner455fcc82005-10-29 03:19:53 +00006857 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6858 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006859 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6860 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006861
Chris Lattner455fcc82005-10-29 03:19:53 +00006862 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6863 Value *Amt = 0;
6864 if (Scale == 1) {
6865 Amt = NumElements;
6866 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006867 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006868 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6869 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006870 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006871 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006872 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006873 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006874 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006875 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006876 }
6877
Jeff Cohen86796be2007-04-04 16:58:57 +00006878 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6879 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006880 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006881 Amt = InsertNewInstBefore(Tmp, AI);
6882 }
6883
Chris Lattnerb3f83972005-10-24 06:03:58 +00006884 AllocationInst *New;
6885 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006886 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006887 else
Chris Lattner6934a042007-02-11 01:23:03 +00006888 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006889 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006890 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006891
6892 // If the allocation has multiple uses, insert a cast and change all things
6893 // that used it to use the new cast. This will also hack on CI, but it will
6894 // die soon.
6895 if (!AI.hasOneUse()) {
6896 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006897 // New is the allocation instruction, pointer typed. AI is the original
6898 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6899 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006900 InsertNewInstBefore(NewCast, AI);
6901 AI.replaceAllUsesWith(NewCast);
6902 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006903 return ReplaceInstUsesWith(CI, New);
6904}
6905
Chris Lattner70074e02006-05-13 02:06:03 +00006906/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006907/// and return it as type Ty without inserting any new casts and without
6908/// changing the computed value. This is used by code that tries to decide
6909/// whether promoting or shrinking integer operations to wider or smaller types
6910/// will allow us to eliminate a truncate or extend.
6911///
6912/// This is a truncation operation if Ty is smaller than V->getType(), or an
6913/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006914///
6915/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6916/// should return true if trunc(V) can be computed by computing V in the smaller
6917/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6918/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6919/// efficiently truncated.
6920///
6921/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6922/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6923/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006924bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6925 unsigned CastOpc,
6926 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006927 // We can always evaluate constants in another type.
6928 if (isa<ConstantInt>(V))
6929 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006930
6931 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006932 if (!I) return false;
6933
6934 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006935
Chris Lattner951626b2007-08-02 06:11:14 +00006936 // If this is an extension or truncate, we can often eliminate it.
6937 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6938 // If this is a cast from the destination type, we can trivially eliminate
6939 // it, and this will remove a cast overall.
6940 if (I->getOperand(0)->getType() == Ty) {
6941 // If the first operand is itself a cast, and is eliminable, do not count
6942 // this as an eliminable cast. We would prefer to eliminate those two
6943 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00006944 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00006945 ++NumCastsRemoved;
6946 return true;
6947 }
6948 }
6949
6950 // We can't extend or shrink something that has multiple uses: doing so would
6951 // require duplicating the instruction in general, which isn't profitable.
6952 if (!I->hasOneUse()) return false;
6953
Chris Lattner70074e02006-05-13 02:06:03 +00006954 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006955 case Instruction::Add:
6956 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00006957 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006958 case Instruction::And:
6959 case Instruction::Or:
6960 case Instruction::Xor:
6961 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6963 NumCastsRemoved) &&
6964 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6965 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006966
Chris Lattner46b96052006-11-29 07:18:39 +00006967 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006968 // If we are truncating the result of this SHL, and if it's a shift of a
6969 // constant amount, we can always perform a SHL in a smaller type.
6970 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006971 uint32_t BitWidth = Ty->getBitWidth();
6972 if (BitWidth < OrigTy->getBitWidth() &&
6973 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006974 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6975 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006976 }
6977 break;
6978 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006979 // If this is a truncate of a logical shr, we can truncate it to a smaller
6980 // lshr iff we know that the bits we would otherwise be shifting in are
6981 // already zeros.
6982 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006983 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6984 uint32_t BitWidth = Ty->getBitWidth();
6985 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006986 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006987 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6988 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006989 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6990 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006991 }
6992 }
Chris Lattner46b96052006-11-29 07:18:39 +00006993 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006994 case Instruction::ZExt:
6995 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006996 case Instruction::Trunc:
6997 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006998 // can safely replace it. Note that replacing it does not reduce the number
6999 // of casts in the input.
7000 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007001 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007002 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007003 case Instruction::Select: {
7004 SelectInst *SI = cast<SelectInst>(I);
7005 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7006 NumCastsRemoved) &&
7007 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7008 NumCastsRemoved);
7009 }
Chris Lattner8114b712008-06-18 04:00:49 +00007010 case Instruction::PHI: {
7011 // We can change a phi if we can change all operands.
7012 PHINode *PN = cast<PHINode>(I);
7013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7014 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7015 NumCastsRemoved))
7016 return false;
7017 return true;
7018 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007019 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007020 // TODO: Can handle more cases here.
7021 break;
7022 }
7023
7024 return false;
7025}
7026
7027/// EvaluateInDifferentType - Given an expression that
7028/// CanEvaluateInDifferentType returns true for, actually insert the code to
7029/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007030Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007031 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007032 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007033 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007034
7035 // Otherwise, it must be an instruction.
7036 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007037 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007038 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007039 case Instruction::Add:
7040 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007041 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007042 case Instruction::And:
7043 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007044 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007045 case Instruction::AShr:
7046 case Instruction::LShr:
7047 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007048 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007049 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007050 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007051 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007052 break;
7053 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007054 case Instruction::Trunc:
7055 case Instruction::ZExt:
7056 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007057 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007058 // just return the source. There's no need to insert it because it is not
7059 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007060 if (I->getOperand(0)->getType() == Ty)
7061 return I->getOperand(0);
7062
Chris Lattner8114b712008-06-18 04:00:49 +00007063 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007064 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007065 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007066 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007067 case Instruction::Select: {
7068 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7069 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7070 Res = SelectInst::Create(I->getOperand(0), True, False);
7071 break;
7072 }
Chris Lattner8114b712008-06-18 04:00:49 +00007073 case Instruction::PHI: {
7074 PHINode *OPN = cast<PHINode>(I);
7075 PHINode *NPN = PHINode::Create(Ty);
7076 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7077 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7078 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7079 }
7080 Res = NPN;
7081 break;
7082 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007083 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007084 // TODO: Can handle more cases here.
7085 assert(0 && "Unreachable!");
7086 break;
7087 }
7088
Chris Lattner8114b712008-06-18 04:00:49 +00007089 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007090 return InsertNewInstBefore(Res, *I);
7091}
7092
Reid Spencer3da59db2006-11-27 01:05:10 +00007093/// @brief Implement the transforms common to all CastInst visitors.
7094Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007095 Value *Src = CI.getOperand(0);
7096
Dan Gohman23d9d272007-05-11 21:10:54 +00007097 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007098 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007099 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007100 if (Instruction::CastOps opc =
7101 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7102 // The first cast (CSrc) is eliminable so we need to fix up or replace
7103 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007104 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007105 }
7106 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007107
Reid Spencer3da59db2006-11-27 01:05:10 +00007108 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007109 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7110 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7111 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007112
7113 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007114 if (isa<PHINode>(Src))
7115 if (Instruction *NV = FoldOpIntoPhi(CI))
7116 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007117
Reid Spencer3da59db2006-11-27 01:05:10 +00007118 return 0;
7119}
7120
Chris Lattnerd3e28342007-04-27 17:44:50 +00007121/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7122Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7123 Value *Src = CI.getOperand(0);
7124
Chris Lattnerd3e28342007-04-27 17:44:50 +00007125 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007126 // If casting the result of a getelementptr instruction with no offset, turn
7127 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007128 if (GEP->hasAllZeroIndices()) {
7129 // Changing the cast operand is usually not a good idea but it is safe
7130 // here because the pointer operand is being replaced with another
7131 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007132 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007133 CI.setOperand(0, GEP->getOperand(0));
7134 return &CI;
7135 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007136
7137 // If the GEP has a single use, and the base pointer is a bitcast, and the
7138 // GEP computes a constant offset, see if we can convert these three
7139 // instructions into fewer. This typically happens with unions and other
7140 // non-type-safe code.
7141 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7142 if (GEP->hasAllConstantIndices()) {
7143 // We are guaranteed to get a constant from EmitGEPOffset.
7144 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7145 int64_t Offset = OffsetV->getSExtValue();
7146
7147 // Get the base pointer input of the bitcast, and the type it points to.
7148 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7149 const Type *GEPIdxTy =
7150 cast<PointerType>(OrigBase->getType())->getElementType();
7151 if (GEPIdxTy->isSized()) {
7152 SmallVector<Value*, 8> NewIndices;
7153
Chris Lattnerc42e2262007-05-05 01:59:31 +00007154 // Start with the index over the outer type. Note that the type size
7155 // might be zero (even if the offset isn't zero) if the indexed type
7156 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007157 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007158 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007159 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007160 FirstIdx = Offset/TySize;
7161 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007162
Chris Lattnerc42e2262007-05-05 01:59:31 +00007163 // Handle silly modulus not returning values values [0..TySize).
7164 if (Offset < 0) {
7165 --FirstIdx;
7166 Offset += TySize;
7167 assert(Offset >= 0);
7168 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007169 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007170 }
7171
7172 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007173
7174 // Index into the types. If we fail, set OrigBase to null.
7175 while (Offset) {
7176 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7177 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007178 if (Offset < (int64_t)SL->getSizeInBytes()) {
7179 unsigned Elt = SL->getElementContainingOffset(Offset);
7180 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007181
Chris Lattner6b6aef82007-05-15 00:16:00 +00007182 Offset -= SL->getElementOffset(Elt);
7183 GEPIdxTy = STy->getElementType(Elt);
7184 } else {
7185 // Otherwise, we can't index into this, bail out.
7186 Offset = 0;
7187 OrigBase = 0;
7188 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007189 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7190 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007191 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007192 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7193 Offset %= EltSize;
7194 } else {
7195 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7196 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007197 GEPIdxTy = STy->getElementType();
7198 } else {
7199 // Otherwise, we can't index into this, bail out.
7200 Offset = 0;
7201 OrigBase = 0;
7202 }
7203 }
7204 if (OrigBase) {
7205 // If we were able to index down into an element, create the GEP
7206 // and bitcast the result. This eliminates one bitcast, potentially
7207 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007208 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7209 NewIndices.begin(),
7210 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007211 InsertNewInstBefore(NGEP, CI);
7212 NGEP->takeName(GEP);
7213
Chris Lattner9bc14642007-04-28 00:57:34 +00007214 if (isa<BitCastInst>(CI))
7215 return new BitCastInst(NGEP, CI.getType());
7216 assert(isa<PtrToIntInst>(CI));
7217 return new PtrToIntInst(NGEP, CI.getType());
7218 }
7219 }
7220 }
7221 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007222 }
7223
7224 return commonCastTransforms(CI);
7225}
7226
7227
7228
Chris Lattnerc739cd62007-03-03 05:27:34 +00007229/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7230/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007231/// cases.
7232/// @brief Implement the transforms common to CastInst with integer operands
7233Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7234 if (Instruction *Result = commonCastTransforms(CI))
7235 return Result;
7236
7237 Value *Src = CI.getOperand(0);
7238 const Type *SrcTy = Src->getType();
7239 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007240 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7241 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007242
Reid Spencer3da59db2006-11-27 01:05:10 +00007243 // See if we can simplify any instructions used by the LHS whose sole
7244 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007245 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7246 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007247 KnownZero, KnownOne))
7248 return &CI;
7249
7250 // If the source isn't an instruction or has more than one use then we
7251 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 Instruction *SrcI = dyn_cast<Instruction>(Src);
7253 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007254 return 0;
7255
Chris Lattnerc739cd62007-03-03 05:27:34 +00007256 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007257 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007258 if (!isa<BitCastInst>(CI) &&
7259 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007260 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007261 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007262 // eliminates the cast, so it is always a win. If this is a zero-extension,
7263 // we need to do an AND to maintain the clear top-part of the computation,
7264 // so we require that the input have eliminated at least one cast. If this
7265 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007266 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007267 bool DoXForm;
7268 switch (CI.getOpcode()) {
7269 default:
7270 // All the others use floating point so we shouldn't actually
7271 // get here because of the check above.
7272 assert(0 && "Unknown cast type");
7273 case Instruction::Trunc:
7274 DoXForm = true;
7275 break;
7276 case Instruction::ZExt:
7277 DoXForm = NumCastsRemoved >= 1;
7278 break;
7279 case Instruction::SExt:
7280 DoXForm = NumCastsRemoved >= 2;
7281 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007282 }
7283
7284 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007285 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7286 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007287 assert(Res->getType() == DestTy);
7288 switch (CI.getOpcode()) {
7289 default: assert(0 && "Unknown cast type!");
7290 case Instruction::Trunc:
7291 case Instruction::BitCast:
7292 // Just replace this cast with the result.
7293 return ReplaceInstUsesWith(CI, Res);
7294 case Instruction::ZExt: {
7295 // We need to emit an AND to clear the high bits.
7296 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007297 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7298 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007299 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007300 }
7301 case Instruction::SExt:
7302 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007303 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007304 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7305 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007306 }
7307 }
7308 }
7309
7310 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7311 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7312
7313 switch (SrcI->getOpcode()) {
7314 case Instruction::Add:
7315 case Instruction::Mul:
7316 case Instruction::And:
7317 case Instruction::Or:
7318 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007319 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007320 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7321 // Don't insert two casts if they cannot be eliminated. We allow
7322 // two casts to be inserted if the sizes are the same. This could
7323 // only be converting signedness, which is a noop.
7324 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007325 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7326 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007327 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007328 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7329 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007331 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007332 }
7333 }
7334
7335 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7336 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7337 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007338 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007339 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007340 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007341 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007342 }
7343 break;
7344 case Instruction::SDiv:
7345 case Instruction::UDiv:
7346 case Instruction::SRem:
7347 case Instruction::URem:
7348 // If we are just changing the sign, rewrite.
7349 if (DestBitSize == SrcBitSize) {
7350 // Don't insert two casts if they cannot be eliminated. We allow
7351 // two casts to be inserted if the sizes are the same. This could
7352 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007353 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7354 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007355 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7356 Op0, DestTy, SrcI);
7357 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7358 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007359 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007360 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7361 }
7362 }
7363 break;
7364
7365 case Instruction::Shl:
7366 // Allow changing the sign of the source operand. Do not allow
7367 // changing the size of the shift, UNLESS the shift amount is a
7368 // constant. We must not change variable sized shifts to a smaller
7369 // size, because it is undefined to shift more bits out than exist
7370 // in the value.
7371 if (DestBitSize == SrcBitSize ||
7372 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007373 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7374 Instruction::BitCast : Instruction::Trunc);
7375 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007376 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007377 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007378 }
7379 break;
7380 case Instruction::AShr:
7381 // If this is a signed shr, and if all bits shifted in are about to be
7382 // truncated off, turn it into an unsigned shr to allow greater
7383 // simplifications.
7384 if (DestBitSize < SrcBitSize &&
7385 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007386 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007387 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7388 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007390 }
7391 }
7392 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007393 }
7394 return 0;
7395}
7396
Chris Lattner8a9f5712007-04-11 06:57:46 +00007397Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007398 if (Instruction *Result = commonIntCastTransforms(CI))
7399 return Result;
7400
7401 Value *Src = CI.getOperand(0);
7402 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007403 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7404 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007405
7406 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7407 switch (SrcI->getOpcode()) {
7408 default: break;
7409 case Instruction::LShr:
7410 // We can shrink lshr to something smaller if we know the bits shifted in
7411 // are already zeros.
7412 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007413 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007414
7415 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007416 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007417 Value* SrcIOp0 = SrcI->getOperand(0);
7418 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007419 if (ShAmt >= DestBitWidth) // All zeros.
7420 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7421
7422 // Okay, we can shrink this. Truncate the input, then return a new
7423 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007424 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7425 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7426 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007427 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007428 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007429 } else { // This is a variable shr.
7430
7431 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7432 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7433 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007434 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007435 Value *One = ConstantInt::get(SrcI->getType(), 1);
7436
Reid Spencer832254e2007-02-02 02:16:23 +00007437 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007438 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007439 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007441 SrcI->getOperand(0),
7442 "tmp"), CI);
7443 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007444 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007445 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007446 }
7447 break;
7448 }
7449 }
7450
7451 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007452}
7453
Evan Chengb98a10e2008-03-24 00:21:34 +00007454/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7455/// in order to eliminate the icmp.
7456Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7457 bool DoXform) {
7458 // If we are just checking for a icmp eq of a single bit and zext'ing it
7459 // to an integer, then shift the bit to the appropriate place and then
7460 // cast to integer to avoid the comparison.
7461 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7462 const APInt &Op1CV = Op1C->getValue();
7463
7464 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7465 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7466 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7467 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7468 if (!DoXform) return ICI;
7469
7470 Value *In = ICI->getOperand(0);
7471 Value *Sh = ConstantInt::get(In->getType(),
7472 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007473 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007474 In->getName()+".lobit"),
7475 CI);
7476 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007477 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007478 false/*ZExt*/, "tmp", &CI);
7479
7480 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7481 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007482 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007483 In->getName()+".not"),
7484 CI);
7485 }
7486
7487 return ReplaceInstUsesWith(CI, In);
7488 }
7489
7490
7491
7492 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7493 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7494 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7495 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7496 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7497 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7498 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7499 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7500 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7501 // This only works for EQ and NE
7502 ICI->isEquality()) {
7503 // If Op1C some other power of two, convert:
7504 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7505 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7506 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7507 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7508
7509 APInt KnownZeroMask(~KnownZero);
7510 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7511 if (!DoXform) return ICI;
7512
7513 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7514 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7515 // (X&4) == 2 --> false
7516 // (X&4) != 2 --> true
7517 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7518 Res = ConstantExpr::getZExt(Res, CI.getType());
7519 return ReplaceInstUsesWith(CI, Res);
7520 }
7521
7522 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7523 Value *In = ICI->getOperand(0);
7524 if (ShiftAmt) {
7525 // Perform a logical shr by shiftamt.
7526 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007528 ConstantInt::get(In->getType(), ShiftAmt),
7529 In->getName()+".lobit"), CI);
7530 }
7531
7532 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7533 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007535 InsertNewInstBefore(cast<Instruction>(In), CI);
7536 }
7537
7538 if (CI.getType() == In->getType())
7539 return ReplaceInstUsesWith(CI, In);
7540 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007541 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007542 }
7543 }
7544 }
7545
7546 return 0;
7547}
7548
Chris Lattner8a9f5712007-04-11 06:57:46 +00007549Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007550 // If one of the common conversion will work ..
7551 if (Instruction *Result = commonIntCastTransforms(CI))
7552 return Result;
7553
7554 Value *Src = CI.getOperand(0);
7555
7556 // If this is a cast of a cast
7557 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007558 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7559 // types and if the sizes are just right we can convert this into a logical
7560 // 'and' which will be much cheaper than the pair of casts.
7561 if (isa<TruncInst>(CSrc)) {
7562 // Get the sizes of the types involved
7563 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007564 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7565 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7566 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007567 // If we're actually extending zero bits and the trunc is a no-op
7568 if (MidSize < DstSize && SrcSize == DstSize) {
7569 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007570 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007571 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007572 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007573 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007574 // Unfortunately, if the type changed, we need to cast it back.
7575 if (And->getType() != CI.getType()) {
7576 And->setName(CSrc->getName()+".mask");
7577 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007578 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007579 }
7580 return And;
7581 }
7582 }
7583 }
7584
Evan Chengb98a10e2008-03-24 00:21:34 +00007585 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7586 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007587
Evan Chengb98a10e2008-03-24 00:21:34 +00007588 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7589 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7590 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7591 // of the (zext icmp) will be transformed.
7592 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7593 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7594 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7595 (transformZExtICmp(LHS, CI, false) ||
7596 transformZExtICmp(RHS, CI, false))) {
7597 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7598 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007599 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007600 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007601 }
7602
Reid Spencer3da59db2006-11-27 01:05:10 +00007603 return 0;
7604}
7605
Chris Lattner8a9f5712007-04-11 06:57:46 +00007606Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007607 if (Instruction *I = commonIntCastTransforms(CI))
7608 return I;
7609
Chris Lattner8a9f5712007-04-11 06:57:46 +00007610 Value *Src = CI.getOperand(0);
7611
7612 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7613 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7614 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7615 // If we are just checking for a icmp eq of a single bit and zext'ing it
7616 // to an integer, then shift the bit to the appropriate place and then
7617 // cast to integer to avoid the comparison.
7618 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7619 const APInt &Op1CV = Op1C->getValue();
7620
7621 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7622 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7623 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7624 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7625 Value *In = ICI->getOperand(0);
7626 Value *Sh = ConstantInt::get(In->getType(),
7627 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007628 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007629 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007630 CI);
7631 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007632 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007633 true/*SExt*/, "tmp", &CI);
7634
7635 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007637 In->getName()+".not"), CI);
7638
7639 return ReplaceInstUsesWith(CI, In);
7640 }
7641 }
7642 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007643
7644 // See if the value being truncated is already sign extended. If so, just
7645 // eliminate the trunc/sext pair.
7646 if (getOpcode(Src) == Instruction::Trunc) {
7647 Value *Op = cast<User>(Src)->getOperand(0);
7648 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7649 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7650 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7651 unsigned NumSignBits = ComputeNumSignBits(Op);
7652
7653 if (OpBits == DestBits) {
7654 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7655 // bits, it is already ready.
7656 if (NumSignBits > DestBits-MidBits)
7657 return ReplaceInstUsesWith(CI, Op);
7658 } else if (OpBits < DestBits) {
7659 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7660 // bits, just sext from i32.
7661 if (NumSignBits > OpBits-MidBits)
7662 return new SExtInst(Op, CI.getType(), "tmp");
7663 } else {
7664 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7665 // bits, just truncate to i32.
7666 if (NumSignBits > OpBits-MidBits)
7667 return new TruncInst(Op, CI.getType(), "tmp");
7668 }
7669 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007670
Chris Lattnerba417832007-04-11 06:12:58 +00007671 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007672}
7673
Chris Lattnerb7530652008-01-27 05:29:54 +00007674/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7675/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007676static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007677 APFloat F = CFP->getValueAPF();
7678 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007679 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007680 return 0;
7681}
7682
7683/// LookThroughFPExtensions - If this is an fp extension instruction, look
7684/// through it until we get the source value.
7685static Value *LookThroughFPExtensions(Value *V) {
7686 if (Instruction *I = dyn_cast<Instruction>(V))
7687 if (I->getOpcode() == Instruction::FPExt)
7688 return LookThroughFPExtensions(I->getOperand(0));
7689
7690 // If this value is a constant, return the constant in the smallest FP type
7691 // that can accurately represent it. This allows us to turn
7692 // (float)((double)X+2.0) into x+2.0f.
7693 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7694 if (CFP->getType() == Type::PPC_FP128Ty)
7695 return V; // No constant folding of this.
7696 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007697 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007698 return V;
7699 if (CFP->getType() == Type::DoubleTy)
7700 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007701 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007702 return V;
7703 // Don't try to shrink to various long double types.
7704 }
7705
7706 return V;
7707}
7708
7709Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7710 if (Instruction *I = commonCastTransforms(CI))
7711 return I;
7712
7713 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7714 // smaller than the destination type, we can eliminate the truncate by doing
7715 // the add as the smaller type. This applies to add/sub/mul/div as well as
7716 // many builtins (sqrt, etc).
7717 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7718 if (OpI && OpI->hasOneUse()) {
7719 switch (OpI->getOpcode()) {
7720 default: break;
7721 case Instruction::Add:
7722 case Instruction::Sub:
7723 case Instruction::Mul:
7724 case Instruction::FDiv:
7725 case Instruction::FRem:
7726 const Type *SrcTy = OpI->getType();
7727 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7728 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7729 if (LHSTrunc->getType() != SrcTy &&
7730 RHSTrunc->getType() != SrcTy) {
7731 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7732 // If the source types were both smaller than the destination type of
7733 // the cast, do this xform.
7734 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7735 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7736 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7737 CI.getType(), CI);
7738 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7739 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007740 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007741 }
7742 }
7743 break;
7744 }
7745 }
7746 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007747}
7748
7749Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7750 return commonCastTransforms(CI);
7751}
7752
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007753Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7754 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7755 // mantissa to accurately represent all values of X. For example, do not
7756 // do this with i64->float->i64.
7757 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7758 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7759 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007760 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007761 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7762
7763 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007764}
7765
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007766Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7767 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7768 // mantissa to accurately represent all values of X. For example, do not
7769 // do this with i64->float->i64.
7770 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7771 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7772 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007773 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007774 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7775
7776 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007777}
7778
7779Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7780 return commonCastTransforms(CI);
7781}
7782
7783Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7784 return commonCastTransforms(CI);
7785}
7786
7787Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007788 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007789}
7790
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007791Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7792 if (Instruction *I = commonCastTransforms(CI))
7793 return I;
7794
7795 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7796 if (!DestPointee->isSized()) return 0;
7797
7798 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7799 ConstantInt *Cst;
7800 Value *X;
7801 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7802 m_ConstantInt(Cst)))) {
7803 // If the source and destination operands have the same type, see if this
7804 // is a single-index GEP.
7805 if (X->getType() == CI.getType()) {
7806 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007807 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007808
7809 // Convert the constant to intptr type.
7810 APInt Offset = Cst->getValue();
7811 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7812
7813 // If Offset is evenly divisible by Size, we can do this xform.
7814 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7815 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007816 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007817 }
7818 }
7819 // TODO: Could handle other cases, e.g. where add is indexing into field of
7820 // struct etc.
7821 } else if (CI.getOperand(0)->hasOneUse() &&
7822 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7823 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7824 // "inttoptr+GEP" instead of "add+intptr".
7825
7826 // Get the size of the pointee type.
7827 uint64_t Size = TD->getABITypeSize(DestPointee);
7828
7829 // Convert the constant to intptr type.
7830 APInt Offset = Cst->getValue();
7831 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7832
7833 // If Offset is evenly divisible by Size, we can do this xform.
7834 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7835 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7836
7837 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7838 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007839 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007840 }
7841 }
7842 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007843}
7844
Chris Lattnerd3e28342007-04-27 17:44:50 +00007845Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007846 // If the operands are integer typed then apply the integer transforms,
7847 // otherwise just apply the common ones.
7848 Value *Src = CI.getOperand(0);
7849 const Type *SrcTy = Src->getType();
7850 const Type *DestTy = CI.getType();
7851
Chris Lattner42a75512007-01-15 02:27:26 +00007852 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007853 if (Instruction *Result = commonIntCastTransforms(CI))
7854 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007855 } else if (isa<PointerType>(SrcTy)) {
7856 if (Instruction *I = commonPointerCastTransforms(CI))
7857 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007858 } else {
7859 if (Instruction *Result = commonCastTransforms(CI))
7860 return Result;
7861 }
7862
7863
7864 // Get rid of casts from one type to the same type. These are useless and can
7865 // be replaced by the operand.
7866 if (DestTy == Src->getType())
7867 return ReplaceInstUsesWith(CI, Src);
7868
Reid Spencer3da59db2006-11-27 01:05:10 +00007869 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007870 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7871 const Type *DstElTy = DstPTy->getElementType();
7872 const Type *SrcElTy = SrcPTy->getElementType();
7873
Nate Begeman83ad90a2008-03-31 00:22:16 +00007874 // If the address spaces don't match, don't eliminate the bitcast, which is
7875 // required for changing types.
7876 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7877 return 0;
7878
Chris Lattnerd3e28342007-04-27 17:44:50 +00007879 // If we are casting a malloc or alloca to a pointer to a type of the same
7880 // size, rewrite the allocation instruction to allocate the "right" type.
7881 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7882 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7883 return V;
7884
Chris Lattnerd717c182007-05-05 22:32:24 +00007885 // If the source and destination are pointers, and this cast is equivalent
7886 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007887 // This can enhance SROA and other transforms that want type-safe pointers.
7888 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7889 unsigned NumZeros = 0;
7890 while (SrcElTy != DstElTy &&
7891 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7892 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7893 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7894 ++NumZeros;
7895 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007896
Chris Lattnerd3e28342007-04-27 17:44:50 +00007897 // If we found a path from the src to dest, create the getelementptr now.
7898 if (SrcElTy == DstElTy) {
7899 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007900 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7901 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007902 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007903 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007904
Reid Spencer3da59db2006-11-27 01:05:10 +00007905 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7906 if (SVI->hasOneUse()) {
7907 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7908 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007909 if (isa<VectorType>(DestTy) &&
7910 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 SVI->getType()->getNumElements()) {
7912 CastInst *Tmp;
7913 // If either of the operands is a cast from CI.getType(), then
7914 // evaluating the shuffle in the casted destination's type will allow
7915 // us to eliminate at least one cast.
7916 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7917 Tmp->getOperand(0)->getType() == DestTy) ||
7918 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7919 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007920 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7921 SVI->getOperand(0), DestTy, &CI);
7922 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7923 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 // Return a new shuffle vector. Use the same element ID's, as we
7925 // know the vector types match #elts.
7926 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007927 }
7928 }
7929 }
7930 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007931 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007932}
7933
Chris Lattnere576b912004-04-09 23:46:01 +00007934/// GetSelectFoldableOperands - We want to turn code that looks like this:
7935/// %C = or %A, %B
7936/// %D = select %cond, %C, %A
7937/// into:
7938/// %C = select %cond, %B, 0
7939/// %D = or %A, %C
7940///
7941/// Assuming that the specified instruction is an operand to the select, return
7942/// a bitmask indicating which operands of this instruction are foldable if they
7943/// equal the other incoming value of the select.
7944///
7945static unsigned GetSelectFoldableOperands(Instruction *I) {
7946 switch (I->getOpcode()) {
7947 case Instruction::Add:
7948 case Instruction::Mul:
7949 case Instruction::And:
7950 case Instruction::Or:
7951 case Instruction::Xor:
7952 return 3; // Can fold through either operand.
7953 case Instruction::Sub: // Can only fold on the amount subtracted.
7954 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007955 case Instruction::LShr:
7956 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007957 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007958 default:
7959 return 0; // Cannot fold
7960 }
7961}
7962
7963/// GetSelectFoldableConstant - For the same transformation as the previous
7964/// function, return the identity constant that goes into the select.
7965static Constant *GetSelectFoldableConstant(Instruction *I) {
7966 switch (I->getOpcode()) {
7967 default: assert(0 && "This cannot happen!"); abort();
7968 case Instruction::Add:
7969 case Instruction::Sub:
7970 case Instruction::Or:
7971 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007972 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007973 case Instruction::LShr:
7974 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007975 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007976 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007977 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007978 case Instruction::Mul:
7979 return ConstantInt::get(I->getType(), 1);
7980 }
7981}
7982
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007983/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7984/// have the same opcode and only one use each. Try to simplify this.
7985Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7986 Instruction *FI) {
7987 if (TI->getNumOperands() == 1) {
7988 // If this is a non-volatile load or a cast from the same type,
7989 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007991 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7992 return 0;
7993 } else {
7994 return 0; // unknown unary op.
7995 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007996
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007997 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007998 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7999 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008000 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008001 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008003 }
8004
Reid Spencer832254e2007-02-02 02:16:23 +00008005 // Only handle binary operators here.
8006 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008007 return 0;
8008
8009 // Figure out if the operations have any operands in common.
8010 Value *MatchOp, *OtherOpT, *OtherOpF;
8011 bool MatchIsOpZero;
8012 if (TI->getOperand(0) == FI->getOperand(0)) {
8013 MatchOp = TI->getOperand(0);
8014 OtherOpT = TI->getOperand(1);
8015 OtherOpF = FI->getOperand(1);
8016 MatchIsOpZero = true;
8017 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8018 MatchOp = TI->getOperand(1);
8019 OtherOpT = TI->getOperand(0);
8020 OtherOpF = FI->getOperand(0);
8021 MatchIsOpZero = false;
8022 } else if (!TI->isCommutative()) {
8023 return 0;
8024 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8025 MatchOp = TI->getOperand(0);
8026 OtherOpT = TI->getOperand(1);
8027 OtherOpF = FI->getOperand(0);
8028 MatchIsOpZero = true;
8029 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8030 MatchOp = TI->getOperand(1);
8031 OtherOpT = TI->getOperand(0);
8032 OtherOpF = FI->getOperand(1);
8033 MatchIsOpZero = true;
8034 } else {
8035 return 0;
8036 }
8037
8038 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008039 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8040 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008041 InsertNewInstBefore(NewSI, SI);
8042
8043 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8044 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008045 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008046 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008048 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008049 assert(0 && "Shouldn't get here");
8050 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008051}
8052
Chris Lattner3d69f462004-03-12 05:52:32 +00008053Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008054 Value *CondVal = SI.getCondition();
8055 Value *TrueVal = SI.getTrueValue();
8056 Value *FalseVal = SI.getFalseValue();
8057
8058 // select true, X, Y -> X
8059 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008060 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008061 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008062
8063 // select C, X, X -> X
8064 if (TrueVal == FalseVal)
8065 return ReplaceInstUsesWith(SI, TrueVal);
8066
Chris Lattnere87597f2004-10-16 18:11:37 +00008067 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8068 return ReplaceInstUsesWith(SI, FalseVal);
8069 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8070 return ReplaceInstUsesWith(SI, TrueVal);
8071 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8072 if (isa<Constant>(TrueVal))
8073 return ReplaceInstUsesWith(SI, TrueVal);
8074 else
8075 return ReplaceInstUsesWith(SI, FalseVal);
8076 }
8077
Reid Spencer4fe16d62007-01-11 18:21:29 +00008078 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008079 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008080 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008081 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008083 } else {
8084 // Change: A = select B, false, C --> A = and !B, C
8085 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008086 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008087 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008088 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008089 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008090 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008091 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008092 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008093 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008094 } else {
8095 // Change: A = select B, C, true --> A = or !B, C
8096 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008097 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008098 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008099 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008100 }
8101 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008102
8103 // select a, b, a -> a&b
8104 // select a, a, b -> a|b
8105 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008107 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008108 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008109 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008110
Chris Lattner2eefe512004-04-09 19:05:30 +00008111 // Selecting between two integer constants?
8112 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8113 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008114 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008115 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008116 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008117 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008118 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008119 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008120 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008121 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008122 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008123 }
Chris Lattnerba417832007-04-11 06:12:58 +00008124
8125 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008126
Reid Spencere4d87aa2006-12-23 06:05:41 +00008127 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008128
Reid Spencere4d87aa2006-12-23 06:05:41 +00008129 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008130 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008131 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008132 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008133 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008134 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008135 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008136 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008137 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008138 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008139 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008140 InsertNewInstBefore(SRA, SI);
8141
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 // Finally, convert to the type of the select RHS. We figure out
8143 // if this requires a SExt, Trunc or BitCast based on the sizes.
8144 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008145 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8146 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008147 if (SRASize < SISize)
8148 opc = Instruction::SExt;
8149 else if (SRASize > SISize)
8150 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008151 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008152 }
8153 }
8154
8155
8156 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008157 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008158 // non-constant value, eliminate this whole mess. This corresponds to
8159 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008160 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008161 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008162 cast<Constant>(IC->getOperand(1))->isNullValue())
8163 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8164 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008165 isa<ConstantInt>(ICA->getOperand(1)) &&
8166 (ICA->getOperand(1) == TrueValC ||
8167 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008168 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8169 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008170 // know whether we have a icmp_ne or icmp_eq and whether the
8171 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008172 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008173 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008174 Value *V = ICA;
8175 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008176 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008177 Instruction::Xor, V, ICA->getOperand(1)), SI);
8178 return ReplaceInstUsesWith(SI, V);
8179 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008180 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008181 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008182
8183 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008184 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8185 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008186 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008187 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8188 // This is not safe in general for floating point:
8189 // consider X== -0, Y== +0.
8190 // It becomes safe if either operand is a nonzero constant.
8191 ConstantFP *CFPt, *CFPf;
8192 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8193 !CFPt->getValueAPF().isZero()) ||
8194 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8195 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008196 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008197 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008198 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008199 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008200 return ReplaceInstUsesWith(SI, TrueVal);
8201 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8202
Reid Spencere4d87aa2006-12-23 06:05:41 +00008203 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008204 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008205 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8206 // This is not safe in general for floating point:
8207 // consider X== -0, Y== +0.
8208 // It becomes safe if either operand is a nonzero constant.
8209 ConstantFP *CFPt, *CFPf;
8210 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8211 !CFPt->getValueAPF().isZero()) ||
8212 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8213 !CFPf->getValueAPF().isZero()))
8214 return ReplaceInstUsesWith(SI, FalseVal);
8215 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008216 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008217 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8218 return ReplaceInstUsesWith(SI, TrueVal);
8219 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8220 }
8221 }
8222
8223 // See if we are selecting two values based on a comparison of the two values.
8224 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8225 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8226 // Transform (X == Y) ? X : Y -> Y
8227 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8228 return ReplaceInstUsesWith(SI, FalseVal);
8229 // Transform (X != Y) ? X : Y -> X
8230 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8231 return ReplaceInstUsesWith(SI, TrueVal);
8232 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8233
8234 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8235 // Transform (X == Y) ? Y : X -> X
8236 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8237 return ReplaceInstUsesWith(SI, FalseVal);
8238 // Transform (X != Y) ? Y : X -> Y
8239 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008240 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008241 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8242 }
8243 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008244
Chris Lattner87875da2005-01-13 22:52:24 +00008245 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8246 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8247 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008248 Instruction *AddOp = 0, *SubOp = 0;
8249
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008250 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8251 if (TI->getOpcode() == FI->getOpcode())
8252 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8253 return IV;
8254
8255 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8256 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008257 if (TI->getOpcode() == Instruction::Sub &&
8258 FI->getOpcode() == Instruction::Add) {
8259 AddOp = FI; SubOp = TI;
8260 } else if (FI->getOpcode() == Instruction::Sub &&
8261 TI->getOpcode() == Instruction::Add) {
8262 AddOp = TI; SubOp = FI;
8263 }
8264
8265 if (AddOp) {
8266 Value *OtherAddOp = 0;
8267 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8268 OtherAddOp = AddOp->getOperand(1);
8269 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8270 OtherAddOp = AddOp->getOperand(0);
8271 }
8272
8273 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008274 // So at this point we know we have (Y -> OtherAddOp):
8275 // select C, (add X, Y), (sub X, Z)
8276 Value *NegVal; // Compute -Z
8277 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8278 NegVal = ConstantExpr::getNeg(C);
8279 } else {
8280 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008281 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008282 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008283
8284 Value *NewTrueOp = OtherAddOp;
8285 Value *NewFalseOp = NegVal;
8286 if (AddOp != TI)
8287 std::swap(NewTrueOp, NewFalseOp);
8288 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008289 SelectInst::Create(CondVal, NewTrueOp,
8290 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008291
8292 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008293 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008294 }
8295 }
8296 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008297
Chris Lattnere576b912004-04-09 23:46:01 +00008298 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008299 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008300 // See the comment above GetSelectFoldableOperands for a description of the
8301 // transformation we are doing here.
8302 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8303 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8304 !isa<Constant>(FalseVal))
8305 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8306 unsigned OpToFold = 0;
8307 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8308 OpToFold = 1;
8309 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8310 OpToFold = 2;
8311 }
8312
8313 if (OpToFold) {
8314 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008315 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008316 SelectInst::Create(SI.getCondition(),
8317 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008318 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008319 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008320 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008321 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008322 else {
8323 assert(0 && "Unknown instruction!!");
8324 }
8325 }
8326 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008327
Chris Lattnere576b912004-04-09 23:46:01 +00008328 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8329 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8330 !isa<Constant>(TrueVal))
8331 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8332 unsigned OpToFold = 0;
8333 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8334 OpToFold = 1;
8335 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8336 OpToFold = 2;
8337 }
8338
8339 if (OpToFold) {
8340 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008341 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008342 SelectInst::Create(SI.getCondition(), C,
8343 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008344 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008345 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008346 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008348 else
Chris Lattnere576b912004-04-09 23:46:01 +00008349 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008350 }
8351 }
8352 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008353
8354 if (BinaryOperator::isNot(CondVal)) {
8355 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8356 SI.setOperand(1, FalseVal);
8357 SI.setOperand(2, TrueVal);
8358 return &SI;
8359 }
8360
Chris Lattner3d69f462004-03-12 05:52:32 +00008361 return 0;
8362}
8363
Dan Gohmaneee962e2008-04-10 18:43:06 +00008364/// EnforceKnownAlignment - If the specified pointer points to an object that
8365/// we control, modify the object's alignment to PrefAlign. This isn't
8366/// often possible though. If alignment is important, a more reliable approach
8367/// is to simply align all global variables and allocation instructions to
8368/// their preferred alignment from the beginning.
8369///
8370static unsigned EnforceKnownAlignment(Value *V,
8371 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008372
Dan Gohmaneee962e2008-04-10 18:43:06 +00008373 User *U = dyn_cast<User>(V);
8374 if (!U) return Align;
8375
8376 switch (getOpcode(U)) {
8377 default: break;
8378 case Instruction::BitCast:
8379 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8380 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008381 // If all indexes are zero, it is just the alignment of the base pointer.
8382 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008383 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008384 if (!isa<Constant>(*i) ||
8385 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008386 AllZeroOperands = false;
8387 break;
8388 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008389
8390 if (AllZeroOperands) {
8391 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008392 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008393 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008394 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008395 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008396 }
8397
8398 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8399 // If there is a large requested alignment and we can, bump up the alignment
8400 // of the global.
8401 if (!GV->isDeclaration()) {
8402 GV->setAlignment(PrefAlign);
8403 Align = PrefAlign;
8404 }
8405 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8406 // If there is a requested alignment and if this is an alloca, round up. We
8407 // don't do this for malloc, because some systems can't respect the request.
8408 if (isa<AllocaInst>(AI)) {
8409 AI->setAlignment(PrefAlign);
8410 Align = PrefAlign;
8411 }
8412 }
8413
8414 return Align;
8415}
8416
8417/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8418/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8419/// and it is more than the alignment of the ultimate object, see if we can
8420/// increase the alignment of the ultimate object, making this check succeed.
8421unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8422 unsigned PrefAlign) {
8423 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8424 sizeof(PrefAlign) * CHAR_BIT;
8425 APInt Mask = APInt::getAllOnesValue(BitWidth);
8426 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8427 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8428 unsigned TrailZ = KnownZero.countTrailingOnes();
8429 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8430
8431 if (PrefAlign > Align)
8432 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8433
8434 // We don't need to make any adjustment.
8435 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008436}
8437
Chris Lattnerf497b022008-01-13 23:50:23 +00008438Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008439 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8440 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008441 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8442 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8443
8444 if (CopyAlign < MinAlign) {
8445 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8446 return MI;
8447 }
8448
8449 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8450 // load/store.
8451 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8452 if (MemOpLength == 0) return 0;
8453
Chris Lattner37ac6082008-01-14 00:28:35 +00008454 // Source and destination pointer types are always "i8*" for intrinsic. See
8455 // if the size is something we can handle with a single primitive load/store.
8456 // A single load+store correctly handles overlapping memory in the memmove
8457 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008458 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008459 if (Size == 0) return MI; // Delete this mem transfer.
8460
8461 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008462 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008463
Chris Lattner37ac6082008-01-14 00:28:35 +00008464 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008465 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008466
8467 // Memcpy forces the use of i8* for the source and destination. That means
8468 // that if you're using memcpy to move one double around, you'll get a cast
8469 // from double* to i8*. We'd much rather use a double load+store rather than
8470 // an i64 load+store, here because this improves the odds that the source or
8471 // dest address will be promotable. See if we can find a better type than the
8472 // integer datatype.
8473 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8474 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8475 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8476 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8477 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008478 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008479 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8480 if (STy->getNumElements() == 1)
8481 SrcETy = STy->getElementType(0);
8482 else
8483 break;
8484 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8485 if (ATy->getNumElements() == 1)
8486 SrcETy = ATy->getElementType();
8487 else
8488 break;
8489 } else
8490 break;
8491 }
8492
Dan Gohman8f8e2692008-05-23 01:52:21 +00008493 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008494 NewPtrTy = PointerType::getUnqual(SrcETy);
8495 }
8496 }
8497
8498
Chris Lattnerf497b022008-01-13 23:50:23 +00008499 // If the memcpy/memmove provides better alignment info than we can
8500 // infer, use it.
8501 SrcAlign = std::max(SrcAlign, CopyAlign);
8502 DstAlign = std::max(DstAlign, CopyAlign);
8503
8504 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8505 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008506 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8507 InsertNewInstBefore(L, *MI);
8508 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8509
8510 // Set the size of the copy to 0, it will be deleted on the next iteration.
8511 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8512 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008513}
Chris Lattner3d69f462004-03-12 05:52:32 +00008514
Chris Lattner69ea9d22008-04-30 06:39:11 +00008515Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8516 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8517 if (MI->getAlignment()->getZExtValue() < Alignment) {
8518 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8519 return MI;
8520 }
8521
8522 // Extract the length and alignment and fill if they are constant.
8523 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8524 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8525 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8526 return 0;
8527 uint64_t Len = LenC->getZExtValue();
8528 Alignment = MI->getAlignment()->getZExtValue();
8529
8530 // If the length is zero, this is a no-op
8531 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8532
8533 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8534 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8535 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8536
8537 Value *Dest = MI->getDest();
8538 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8539
8540 // Alignment 0 is identity for alignment 1 for memset, but not store.
8541 if (Alignment == 0) Alignment = 1;
8542
8543 // Extract the fill value and store.
8544 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8545 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8546 Alignment), *MI);
8547
8548 // Set the size of the copy to 0, it will be deleted on the next iteration.
8549 MI->setLength(Constant::getNullValue(LenC->getType()));
8550 return MI;
8551 }
8552
8553 return 0;
8554}
8555
8556
Chris Lattner8b0ea312006-01-13 20:11:04 +00008557/// visitCallInst - CallInst simplification. This mostly only handles folding
8558/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8559/// the heavy lifting.
8560///
Chris Lattner9fe38862003-06-19 17:00:31 +00008561Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008562 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8563 if (!II) return visitCallSite(&CI);
8564
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008565 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8566 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008567 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008568 bool Changed = false;
8569
8570 // memmove/cpy/set of zero bytes is a noop.
8571 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8572 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8573
Chris Lattner35b9e482004-10-12 04:52:52 +00008574 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008575 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008576 // Replace the instruction with just byte operations. We would
8577 // transform other cases to loads/stores, but we don't know if
8578 // alignment is sufficient.
8579 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008580 }
8581
Chris Lattner35b9e482004-10-12 04:52:52 +00008582 // If we have a memmove and the source operation is a constant global,
8583 // then the source and dest pointers can't alias, so we can change this
8584 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008585 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008586 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8587 if (GVSrc->isConstant()) {
8588 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008589 Intrinsic::ID MemCpyID;
8590 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8591 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008592 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008593 MemCpyID = Intrinsic::memcpy_i64;
8594 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008595 Changed = true;
8596 }
Chris Lattnera935db82008-05-28 05:30:41 +00008597
8598 // memmove(x,x,size) -> noop.
8599 if (MMI->getSource() == MMI->getDest())
8600 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008601 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008602
Chris Lattner95a959d2006-03-06 20:18:44 +00008603 // If we can determine a pointer alignment that is bigger than currently
8604 // set, update the alignment.
8605 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008606 if (Instruction *I = SimplifyMemTransfer(MI))
8607 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008608 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8609 if (Instruction *I = SimplifyMemSet(MSI))
8610 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008611 }
8612
Chris Lattner8b0ea312006-01-13 20:11:04 +00008613 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008614 }
8615
8616 switch (II->getIntrinsicID()) {
8617 default: break;
8618 case Intrinsic::bswap:
8619 // bswap(bswap(x)) -> x
8620 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8621 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8622 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8623 break;
8624 case Intrinsic::ppc_altivec_lvx:
8625 case Intrinsic::ppc_altivec_lvxl:
8626 case Intrinsic::x86_sse_loadu_ps:
8627 case Intrinsic::x86_sse2_loadu_pd:
8628 case Intrinsic::x86_sse2_loadu_dq:
8629 // Turn PPC lvx -> load if the pointer is known aligned.
8630 // Turn X86 loadups -> load if the pointer is known aligned.
8631 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8632 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8633 PointerType::getUnqual(II->getType()),
8634 CI);
8635 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008636 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008637 break;
8638 case Intrinsic::ppc_altivec_stvx:
8639 case Intrinsic::ppc_altivec_stvxl:
8640 // Turn stvx -> store if the pointer is known aligned.
8641 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8642 const Type *OpPtrTy =
8643 PointerType::getUnqual(II->getOperand(1)->getType());
8644 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8645 return new StoreInst(II->getOperand(1), Ptr);
8646 }
8647 break;
8648 case Intrinsic::x86_sse_storeu_ps:
8649 case Intrinsic::x86_sse2_storeu_pd:
8650 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00008651 // Turn X86 storeu -> store if the pointer is known aligned.
8652 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8653 const Type *OpPtrTy =
8654 PointerType::getUnqual(II->getOperand(2)->getType());
8655 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8656 return new StoreInst(II->getOperand(2), Ptr);
8657 }
8658 break;
8659
8660 case Intrinsic::x86_sse_cvttss2si: {
8661 // These intrinsics only demands the 0th element of its input vector. If
8662 // we can simplify the input based on that, do so now.
8663 uint64_t UndefElts;
8664 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8665 UndefElts)) {
8666 II->setOperand(1, V);
8667 return II;
8668 }
8669 break;
8670 }
8671
8672 case Intrinsic::ppc_altivec_vperm:
8673 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8674 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8675 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008676
Chris Lattner0521e3c2008-06-18 04:33:20 +00008677 // Check that all of the elements are integer constants or undefs.
8678 bool AllEltsOk = true;
8679 for (unsigned i = 0; i != 16; ++i) {
8680 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8681 !isa<UndefValue>(Mask->getOperand(i))) {
8682 AllEltsOk = false;
8683 break;
8684 }
8685 }
8686
8687 if (AllEltsOk) {
8688 // Cast the input vectors to byte vectors.
8689 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8690 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8691 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008692
Chris Lattner0521e3c2008-06-18 04:33:20 +00008693 // Only extract each element once.
8694 Value *ExtractedElts[32];
8695 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8696
Chris Lattnere2ed0572006-04-06 19:19:17 +00008697 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008698 if (isa<UndefValue>(Mask->getOperand(i)))
8699 continue;
8700 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8701 Idx &= 31; // Match the hardware behavior.
8702
8703 if (ExtractedElts[Idx] == 0) {
8704 Instruction *Elt =
8705 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8706 InsertNewInstBefore(Elt, CI);
8707 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008708 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008709
Chris Lattner0521e3c2008-06-18 04:33:20 +00008710 // Insert this value into the result vector.
8711 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8712 i, "tmp");
8713 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008714 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008715 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008716 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008717 }
8718 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008719
Chris Lattner0521e3c2008-06-18 04:33:20 +00008720 case Intrinsic::stackrestore: {
8721 // If the save is right next to the restore, remove the restore. This can
8722 // happen when variable allocas are DCE'd.
8723 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8724 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8725 BasicBlock::iterator BI = SS;
8726 if (&*++BI == II)
8727 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008728 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008729 }
8730
8731 // Scan down this block to see if there is another stack restore in the
8732 // same block without an intervening call/alloca.
8733 BasicBlock::iterator BI = II;
8734 TerminatorInst *TI = II->getParent()->getTerminator();
8735 bool CannotRemove = false;
8736 for (++BI; &*BI != TI; ++BI) {
8737 if (isa<AllocaInst>(BI)) {
8738 CannotRemove = true;
8739 break;
8740 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00008741 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8742 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8743 // If there is a stackrestore below this one, remove this one.
8744 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8745 return EraseInstFromFunction(CI);
8746 // Otherwise, ignore the intrinsic.
8747 } else {
8748 // If we found a non-intrinsic call, we can't remove the stack
8749 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008750 CannotRemove = true;
8751 break;
8752 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008753 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008754 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008755
8756 // If the stack restore is in a return/unwind block and if there are no
8757 // allocas or calls between the restore and the return, nuke the restore.
8758 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8759 return EraseInstFromFunction(CI);
8760 break;
8761 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008762 }
8763
Chris Lattner8b0ea312006-01-13 20:11:04 +00008764 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008765}
8766
8767// InvokeInst simplification
8768//
8769Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008770 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008771}
8772
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008773/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8774/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008775static bool isSafeToEliminateVarargsCast(const CallSite CS,
8776 const CastInst * const CI,
8777 const TargetData * const TD,
8778 const int ix) {
8779 if (!CI->isLosslessCast())
8780 return false;
8781
8782 // The size of ByVal arguments is derived from the type, so we
8783 // can't change to a type with a different size. If the size were
8784 // passed explicitly we could avoid this check.
8785 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8786 return true;
8787
8788 const Type* SrcTy =
8789 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8790 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8791 if (!SrcTy->isSized() || !DstTy->isSized())
8792 return false;
8793 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8794 return false;
8795 return true;
8796}
8797
Chris Lattnera44d8a22003-10-07 22:32:43 +00008798// visitCallSite - Improvements for call and invoke instructions.
8799//
8800Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008801 bool Changed = false;
8802
8803 // If the callee is a constexpr cast of a function, attempt to move the cast
8804 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008805 if (transformConstExprCastCall(CS)) return 0;
8806
Chris Lattner6c266db2003-10-07 22:54:13 +00008807 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008808
Chris Lattner08b22ec2005-05-13 07:09:09 +00008809 if (Function *CalleeF = dyn_cast<Function>(Callee))
8810 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8811 Instruction *OldCall = CS.getInstruction();
8812 // If the call and callee calling conventions don't match, this call must
8813 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008814 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008815 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8816 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008817 if (!OldCall->use_empty())
8818 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8819 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8820 return EraseInstFromFunction(*OldCall);
8821 return 0;
8822 }
8823
Chris Lattner17be6352004-10-18 02:59:09 +00008824 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8825 // This instruction is not reachable, just remove it. We insert a store to
8826 // undef so that we know that this code is not reachable, despite the fact
8827 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008828 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008829 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008830 CS.getInstruction());
8831
8832 if (!CS.getInstruction()->use_empty())
8833 CS.getInstruction()->
8834 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8835
8836 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8837 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008838 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8839 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008840 }
Chris Lattner17be6352004-10-18 02:59:09 +00008841 return EraseInstFromFunction(*CS.getInstruction());
8842 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008843
Duncan Sandscdb6d922007-09-17 10:26:40 +00008844 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8845 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8846 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8847 return transformCallThroughTrampoline(CS);
8848
Chris Lattner6c266db2003-10-07 22:54:13 +00008849 const PointerType *PTy = cast<PointerType>(Callee->getType());
8850 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8851 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008852 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008853 // See if we can optimize any arguments passed through the varargs area of
8854 // the call.
8855 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008856 E = CS.arg_end(); I != E; ++I, ++ix) {
8857 CastInst *CI = dyn_cast<CastInst>(*I);
8858 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8859 *I = CI->getOperand(0);
8860 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008861 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008862 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008863 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008864
Duncan Sandsf0c33542007-12-19 21:13:37 +00008865 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008866 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008867 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008868 Changed = true;
8869 }
8870
Chris Lattner6c266db2003-10-07 22:54:13 +00008871 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008872}
8873
Chris Lattner9fe38862003-06-19 17:00:31 +00008874// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8875// attempt to move the cast to the arguments of the call/invoke.
8876//
8877bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8878 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8879 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008880 if (CE->getOpcode() != Instruction::BitCast ||
8881 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008882 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008883 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008884 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008885 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008886
8887 // Okay, this is a cast from a function to a different type. Unless doing so
8888 // would cause a type conversion of one of our arguments, change this call to
8889 // be a direct call with arguments casted to the appropriate types.
8890 //
8891 const FunctionType *FT = Callee->getFunctionType();
8892 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008893 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008894
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008895 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008896 return false; // TODO: Handle multiple return values.
8897
Chris Lattnerf78616b2004-01-14 06:06:08 +00008898 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008899 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008900 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008901 // Conversion is ok if changing from one pointer type to another or from
8902 // a pointer to an integer of the same size.
8903 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00008904 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00008905 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008906
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008907 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008908 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008909 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008910 return false; // Cannot transform this return value.
8911
Chris Lattner58d74912008-03-12 17:45:29 +00008912 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8913 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008914 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008915 return false; // Attribute not compatible with transformed value.
8916 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008917
Chris Lattnerf78616b2004-01-14 06:06:08 +00008918 // If the callsite is an invoke instruction, and the return value is used by
8919 // a PHI node in a successor, we cannot change the return type of the call
8920 // because there is no place to put the cast instruction (without breaking
8921 // the critical edge). Bail out in this case.
8922 if (!Caller->use_empty())
8923 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8924 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8925 UI != E; ++UI)
8926 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8927 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008928 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008929 return false;
8930 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008931
8932 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8933 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008934
Chris Lattner9fe38862003-06-19 17:00:31 +00008935 CallSite::arg_iterator AI = CS.arg_begin();
8936 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8937 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008938 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008939
8940 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008941 return false; // Cannot transform this parameter value.
8942
Chris Lattner58d74912008-03-12 17:45:29 +00008943 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8944 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008945
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008946 // Converting from one pointer type to another or between a pointer and an
8947 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008948 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008949 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8950 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008951 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008952 }
8953
8954 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008955 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008956 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008957
Chris Lattner58d74912008-03-12 17:45:29 +00008958 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8959 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008960 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008961 // won't be dropping them. Check that these extra arguments have attributes
8962 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008963 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8964 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008965 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008966 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008967 if (PAttrs & ParamAttr::VarArgsIncompatible)
8968 return false;
8969 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008970
Chris Lattner9fe38862003-06-19 17:00:31 +00008971 // Okay, we decided that this is a safe thing to do: go ahead and start
8972 // inserting cast instructions as necessary...
8973 std::vector<Value*> Args;
8974 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008975 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008976 attrVec.reserve(NumCommonArgs);
8977
8978 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008979 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008980
8981 // If the return value is not being used, the type may not be compatible
8982 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008983 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008984
8985 // Add the new return attributes.
8986 if (RAttrs)
8987 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008988
8989 AI = CS.arg_begin();
8990 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8991 const Type *ParamTy = FT->getParamType(i);
8992 if ((*AI)->getType() == ParamTy) {
8993 Args.push_back(*AI);
8994 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008995 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008996 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008997 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008998 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008999 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009000
9001 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009002 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009003 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009004 }
9005
9006 // If the function takes more arguments than the call was taking, add them
9007 // now...
9008 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9009 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9010
9011 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009012 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009013 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009014 cerr << "WARNING: While resolving call to function '"
9015 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009016 } else {
9017 // Add all of the arguments in their promoted form to the arg list...
9018 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9019 const Type *PTy = getPromotedType((*AI)->getType());
9020 if (PTy != (*AI)->getType()) {
9021 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009022 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9023 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009024 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009025 InsertNewInstBefore(Cast, *Caller);
9026 Args.push_back(Cast);
9027 } else {
9028 Args.push_back(*AI);
9029 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009030
Duncan Sandse1e520f2008-01-13 08:02:44 +00009031 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009032 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009033 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9034 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009035 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009036 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009037
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009038 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009039 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009040
Chris Lattner58d74912008-03-12 17:45:29 +00009041 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009042
Chris Lattner9fe38862003-06-19 17:00:31 +00009043 Instruction *NC;
9044 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009045 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009046 Args.begin(), Args.end(),
9047 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009048 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009049 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009050 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009051 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9052 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009053 CallInst *CI = cast<CallInst>(Caller);
9054 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009055 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009056 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009057 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009058 }
9059
Chris Lattner6934a042007-02-11 01:23:03 +00009060 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009061 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009062 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009063 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009064 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009065 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009066 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009067
9068 // If this is an invoke instruction, we should insert it after the first
9069 // non-phi, instruction in the normal successor block.
9070 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009071 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009072 InsertNewInstBefore(NC, *I);
9073 } else {
9074 // Otherwise, it's a call, just insert cast right after the call instr
9075 InsertNewInstBefore(NC, *Caller);
9076 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009077 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009078 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009079 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009080 }
9081 }
9082
9083 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9084 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009085 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009086 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009087 return true;
9088}
9089
Duncan Sandscdb6d922007-09-17 10:26:40 +00009090// transformCallThroughTrampoline - Turn a call to a function created by the
9091// init_trampoline intrinsic into a direct call to the underlying function.
9092//
9093Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9094 Value *Callee = CS.getCalledValue();
9095 const PointerType *PTy = cast<PointerType>(Callee->getType());
9096 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009097 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009098
9099 // If the call already has the 'nest' attribute somewhere then give up -
9100 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009101 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009102 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009103
9104 IntrinsicInst *Tramp =
9105 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9106
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009107 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009108 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9109 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9110
Chris Lattner58d74912008-03-12 17:45:29 +00009111 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9112 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009113 unsigned NestIdx = 1;
9114 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009115 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009116
9117 // Look for a parameter marked with the 'nest' attribute.
9118 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9119 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009120 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009121 // Record the parameter type and any other attributes.
9122 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009123 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009124 break;
9125 }
9126
9127 if (NestTy) {
9128 Instruction *Caller = CS.getInstruction();
9129 std::vector<Value*> NewArgs;
9130 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9131
Chris Lattner58d74912008-03-12 17:45:29 +00009132 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9133 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009134
Duncan Sandscdb6d922007-09-17 10:26:40 +00009135 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009136 // mean appending it. Likewise for attributes.
9137
9138 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009139 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9140 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009141
Duncan Sandscdb6d922007-09-17 10:26:40 +00009142 {
9143 unsigned Idx = 1;
9144 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9145 do {
9146 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009147 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009148 Value *NestVal = Tramp->getOperand(3);
9149 if (NestVal->getType() != NestTy)
9150 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9151 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009152 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009153 }
9154
9155 if (I == E)
9156 break;
9157
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009158 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009159 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009160 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009161 NewAttrs.push_back
9162 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009163
9164 ++Idx, ++I;
9165 } while (1);
9166 }
9167
9168 // The trampoline may have been bitcast to a bogus type (FTy).
9169 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009170 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009171
Duncan Sandscdb6d922007-09-17 10:26:40 +00009172 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009173 NewTypes.reserve(FTy->getNumParams()+1);
9174
Duncan Sandscdb6d922007-09-17 10:26:40 +00009175 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009176 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009177 {
9178 unsigned Idx = 1;
9179 FunctionType::param_iterator I = FTy->param_begin(),
9180 E = FTy->param_end();
9181
9182 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009183 if (Idx == NestIdx)
9184 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009185 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009186
9187 if (I == E)
9188 break;
9189
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009190 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009191 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009192
9193 ++Idx, ++I;
9194 } while (1);
9195 }
9196
9197 // Replace the trampoline call with a direct call. Let the generic
9198 // code sort out any function type mismatches.
9199 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009200 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009201 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9202 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009203 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009204
9205 Instruction *NewCaller;
9206 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009207 NewCaller = InvokeInst::Create(NewCallee,
9208 II->getNormalDest(), II->getUnwindDest(),
9209 NewArgs.begin(), NewArgs.end(),
9210 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009211 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009212 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009213 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009214 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9215 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009216 if (cast<CallInst>(Caller)->isTailCall())
9217 cast<CallInst>(NewCaller)->setTailCall();
9218 cast<CallInst>(NewCaller)->
9219 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009220 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009221 }
9222 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9223 Caller->replaceAllUsesWith(NewCaller);
9224 Caller->eraseFromParent();
9225 RemoveFromWorkList(Caller);
9226 return 0;
9227 }
9228 }
9229
9230 // Replace the trampoline call with a direct call. Since there is no 'nest'
9231 // parameter, there is no need to adjust the argument list. Let the generic
9232 // code sort out any function type mismatches.
9233 Constant *NewCallee =
9234 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9235 CS.setCalledFunction(NewCallee);
9236 return CS.getInstruction();
9237}
9238
Chris Lattner7da52b22006-11-01 04:51:18 +00009239/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9240/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9241/// and a single binop.
9242Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9243 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009244 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9245 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009246 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009247 Value *LHSVal = FirstInst->getOperand(0);
9248 Value *RHSVal = FirstInst->getOperand(1);
9249
9250 const Type *LHSType = LHSVal->getType();
9251 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009252
9253 // Scan to see if all operands are the same opcode, all have one use, and all
9254 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009255 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009256 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009257 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009258 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009259 // types or GEP's with different index types.
9260 I->getOperand(0)->getType() != LHSType ||
9261 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009262 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009263
9264 // If they are CmpInst instructions, check their predicates
9265 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9266 if (cast<CmpInst>(I)->getPredicate() !=
9267 cast<CmpInst>(FirstInst)->getPredicate())
9268 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009269
9270 // Keep track of which operand needs a phi node.
9271 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9272 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009273 }
9274
Chris Lattner53738a42006-11-08 19:42:28 +00009275 // Otherwise, this is safe to transform, determine if it is profitable.
9276
9277 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9278 // Indexes are often folded into load/store instructions, so we don't want to
9279 // hide them behind a phi.
9280 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9281 return 0;
9282
Chris Lattner7da52b22006-11-01 04:51:18 +00009283 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009284 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009285 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009286 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009287 NewLHS = PHINode::Create(LHSType,
9288 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009289 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9290 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009291 InsertNewInstBefore(NewLHS, PN);
9292 LHSVal = NewLHS;
9293 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009294
9295 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009296 NewRHS = PHINode::Create(RHSType,
9297 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009298 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9299 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009300 InsertNewInstBefore(NewRHS, PN);
9301 RHSVal = NewRHS;
9302 }
9303
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009304 // Add all operands to the new PHIs.
9305 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9306 if (NewLHS) {
9307 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9308 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9309 }
9310 if (NewRHS) {
9311 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9312 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9313 }
9314 }
9315
Chris Lattner7da52b22006-11-01 04:51:18 +00009316 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009317 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009318 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009319 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009320 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009321 else {
9322 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009323 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009324 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009325}
9326
Chris Lattner76c73142006-11-01 07:13:54 +00009327/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9328/// of the block that defines it. This means that it must be obvious the value
9329/// of the load is not changed from the point of the load to the end of the
9330/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009331///
9332/// Finally, it is safe, but not profitable, to sink a load targetting a
9333/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9334/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009335static bool isSafeToSinkLoad(LoadInst *L) {
9336 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9337
9338 for (++BBI; BBI != E; ++BBI)
9339 if (BBI->mayWriteToMemory())
9340 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009341
9342 // Check for non-address taken alloca. If not address-taken already, it isn't
9343 // profitable to do this xform.
9344 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9345 bool isAddressTaken = false;
9346 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9347 UI != E; ++UI) {
9348 if (isa<LoadInst>(UI)) continue;
9349 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9350 // If storing TO the alloca, then the address isn't taken.
9351 if (SI->getOperand(1) == AI) continue;
9352 }
9353 isAddressTaken = true;
9354 break;
9355 }
9356
9357 if (!isAddressTaken)
9358 return false;
9359 }
9360
Chris Lattner76c73142006-11-01 07:13:54 +00009361 return true;
9362}
9363
Chris Lattner9fe38862003-06-19 17:00:31 +00009364
Chris Lattnerbac32862004-11-14 19:13:23 +00009365// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9366// operator and they all are only used by the PHI, PHI together their
9367// inputs, and do the operation once, to the result of the PHI.
9368Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9369 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9370
9371 // Scan the instruction, looking for input operations that can be folded away.
9372 // If all input operands to the phi are the same instruction (e.g. a cast from
9373 // the same type or "+42") we can pull the operation through the PHI, reducing
9374 // code size and simplifying code.
9375 Constant *ConstantOp = 0;
9376 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009377 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009378 if (isa<CastInst>(FirstInst)) {
9379 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009380 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009381 // Can fold binop, compare or shift here if the RHS is a constant,
9382 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009383 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009384 if (ConstantOp == 0)
9385 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009386 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9387 isVolatile = LI->isVolatile();
9388 // We can't sink the load if the loaded value could be modified between the
9389 // load and the PHI.
9390 if (LI->getParent() != PN.getIncomingBlock(0) ||
9391 !isSafeToSinkLoad(LI))
9392 return 0;
Chris Lattner71042962008-07-08 17:18:32 +00009393
9394 // If the PHI is of volatile loads and the load block has multiple
9395 // successors, sinking it would remove a load of the volatile value from
9396 // the path through the other successor.
9397 if (isVolatile &&
9398 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9399 return 0;
9400
Chris Lattner9c080502006-11-01 07:43:41 +00009401 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009402 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009403 return FoldPHIArgBinOpIntoPHI(PN);
9404 // Can't handle general GEPs yet.
9405 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009406 } else {
9407 return 0; // Cannot fold this operation.
9408 }
9409
9410 // Check to see if all arguments are the same operation.
9411 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9412 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9413 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009414 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009415 return 0;
9416 if (CastSrcTy) {
9417 if (I->getOperand(0)->getType() != CastSrcTy)
9418 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009419 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009420 // We can't sink the load if the loaded value could be modified between
9421 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009422 if (LI->isVolatile() != isVolatile ||
9423 LI->getParent() != PN.getIncomingBlock(i) ||
9424 !isSafeToSinkLoad(LI))
9425 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009426
Chris Lattner71042962008-07-08 17:18:32 +00009427 // If the PHI is of volatile loads and the load block has multiple
9428 // successors, sinking it would remove a load of the volatile value from
9429 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +00009430 if (isVolatile &&
9431 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9432 return 0;
9433
9434
Chris Lattnerbac32862004-11-14 19:13:23 +00009435 } else if (I->getOperand(1) != ConstantOp) {
9436 return 0;
9437 }
9438 }
9439
9440 // Okay, they are all the same operation. Create a new PHI node of the
9441 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009442 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9443 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009444 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009445
9446 Value *InVal = FirstInst->getOperand(0);
9447 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009448
9449 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009450 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9451 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9452 if (NewInVal != InVal)
9453 InVal = 0;
9454 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9455 }
9456
9457 Value *PhiVal;
9458 if (InVal) {
9459 // The new PHI unions all of the same values together. This is really
9460 // common, so we handle it intelligently here for compile-time speed.
9461 PhiVal = InVal;
9462 delete NewPN;
9463 } else {
9464 InsertNewInstBefore(NewPN, PN);
9465 PhiVal = NewPN;
9466 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009467
Chris Lattnerbac32862004-11-14 19:13:23 +00009468 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009469 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009470 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009471 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009472 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009473 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009474 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009476 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9477
9478 // If this was a volatile load that we are merging, make sure to loop through
9479 // and mark all the input loads as non-volatile. If we don't do this, we will
9480 // insert a new volatile load and the old ones will not be deletable.
9481 if (isVolatile)
9482 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9483 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9484
9485 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009486}
Chris Lattnera1be5662002-05-02 17:06:02 +00009487
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009488/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9489/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009490static bool DeadPHICycle(PHINode *PN,
9491 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009492 if (PN->use_empty()) return true;
9493 if (!PN->hasOneUse()) return false;
9494
9495 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009496 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009497 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009498
9499 // Don't scan crazily complex things.
9500 if (PotentiallyDeadPHIs.size() == 16)
9501 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009502
9503 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9504 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009505
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009506 return false;
9507}
9508
Chris Lattnercf5008a2007-11-06 21:52:06 +00009509/// PHIsEqualValue - Return true if this phi node is always equal to
9510/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9511/// z = some value; x = phi (y, z); y = phi (x, z)
9512static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9513 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9514 // See if we already saw this PHI node.
9515 if (!ValueEqualPHIs.insert(PN))
9516 return true;
9517
9518 // Don't scan crazily complex things.
9519 if (ValueEqualPHIs.size() == 16)
9520 return false;
9521
9522 // Scan the operands to see if they are either phi nodes or are equal to
9523 // the value.
9524 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9525 Value *Op = PN->getIncomingValue(i);
9526 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9527 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9528 return false;
9529 } else if (Op != NonPhiInVal)
9530 return false;
9531 }
9532
9533 return true;
9534}
9535
9536
Chris Lattner473945d2002-05-06 18:06:38 +00009537// PHINode simplification
9538//
Chris Lattner7e708292002-06-25 16:13:24 +00009539Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009540 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009541 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009542
Owen Anderson7e057142006-07-10 22:03:18 +00009543 if (Value *V = PN.hasConstantValue())
9544 return ReplaceInstUsesWith(PN, V);
9545
Owen Anderson7e057142006-07-10 22:03:18 +00009546 // If all PHI operands are the same operation, pull them through the PHI,
9547 // reducing code size.
9548 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9549 PN.getIncomingValue(0)->hasOneUse())
9550 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9551 return Result;
9552
9553 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9554 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9555 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009556 if (PN.hasOneUse()) {
9557 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9558 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009559 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009560 PotentiallyDeadPHIs.insert(&PN);
9561 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9562 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9563 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009564
9565 // If this phi has a single use, and if that use just computes a value for
9566 // the next iteration of a loop, delete the phi. This occurs with unused
9567 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9568 // common case here is good because the only other things that catch this
9569 // are induction variable analysis (sometimes) and ADCE, which is only run
9570 // late.
9571 if (PHIUser->hasOneUse() &&
9572 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9573 PHIUser->use_back() == &PN) {
9574 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9575 }
9576 }
Owen Anderson7e057142006-07-10 22:03:18 +00009577
Chris Lattnercf5008a2007-11-06 21:52:06 +00009578 // We sometimes end up with phi cycles that non-obviously end up being the
9579 // same value, for example:
9580 // z = some value; x = phi (y, z); y = phi (x, z)
9581 // where the phi nodes don't necessarily need to be in the same block. Do a
9582 // quick check to see if the PHI node only contains a single non-phi value, if
9583 // so, scan to see if the phi cycle is actually equal to that value.
9584 {
9585 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9586 // Scan for the first non-phi operand.
9587 while (InValNo != NumOperandVals &&
9588 isa<PHINode>(PN.getIncomingValue(InValNo)))
9589 ++InValNo;
9590
9591 if (InValNo != NumOperandVals) {
9592 Value *NonPhiInVal = PN.getOperand(InValNo);
9593
9594 // Scan the rest of the operands to see if there are any conflicts, if so
9595 // there is no need to recursively scan other phis.
9596 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9597 Value *OpVal = PN.getIncomingValue(InValNo);
9598 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9599 break;
9600 }
9601
9602 // If we scanned over all operands, then we have one unique value plus
9603 // phi values. Scan PHI nodes to see if they all merge in each other or
9604 // the value.
9605 if (InValNo == NumOperandVals) {
9606 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9607 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9608 return ReplaceInstUsesWith(PN, NonPhiInVal);
9609 }
9610 }
9611 }
Chris Lattner60921c92003-12-19 05:58:40 +00009612 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009613}
9614
Reid Spencer17212df2006-12-12 09:18:51 +00009615static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9616 Instruction *InsertPoint,
9617 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009618 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9619 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009620 // We must cast correctly to the pointer type. Ensure that we
9621 // sign extend the integer value if it is smaller as this is
9622 // used for address computation.
9623 Instruction::CastOps opcode =
9624 (VTySize < PtrSize ? Instruction::SExt :
9625 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9626 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009627}
9628
Chris Lattnera1be5662002-05-02 17:06:02 +00009629
Chris Lattner7e708292002-06-25 16:13:24 +00009630Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009631 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009632 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009633 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009634 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009635 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009636
Chris Lattnere87597f2004-10-16 18:11:37 +00009637 if (isa<UndefValue>(GEP.getOperand(0)))
9638 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9639
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009640 bool HasZeroPointerIndex = false;
9641 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9642 HasZeroPointerIndex = C->isNullValue();
9643
9644 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009645 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009646
Chris Lattner28977af2004-04-05 01:30:19 +00009647 // Eliminate unneeded casts for indices.
9648 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009649
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009650 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009651 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9652 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009653 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009654 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009655 if (CI->getOpcode() == Instruction::ZExt ||
9656 CI->getOpcode() == Instruction::SExt) {
9657 const Type *SrcTy = CI->getOperand(0)->getType();
9658 // We can eliminate a cast from i32 to i64 iff the target
9659 // is a 32-bit pointer target.
9660 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9661 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009662 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009663 }
9664 }
9665 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009666 // If we are using a wider index than needed for this platform, shrink it
9667 // to what we need. If the incoming value needs a cast instruction,
9668 // insert it. This explicit cast can make subsequent optimizations more
9669 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009670 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009671 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009672 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009673 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009674 MadeChange = true;
9675 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009676 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9677 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009678 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009679 MadeChange = true;
9680 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009681 }
Chris Lattner28977af2004-04-05 01:30:19 +00009682 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009683 }
Chris Lattner28977af2004-04-05 01:30:19 +00009684 if (MadeChange) return &GEP;
9685
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009686 // If this GEP instruction doesn't move the pointer, and if the input operand
9687 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9688 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009689 if (GEP.hasAllZeroIndices()) {
9690 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9691 // If the bitcast is of an allocation, and the allocation will be
9692 // converted to match the type of the cast, don't touch this.
9693 if (isa<AllocationInst>(BCI->getOperand(0))) {
9694 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009695 if (Instruction *I = visitBitCast(*BCI)) {
9696 if (I != BCI) {
9697 I->takeName(BCI);
9698 BCI->getParent()->getInstList().insert(BCI, I);
9699 ReplaceInstUsesWith(*BCI, I);
9700 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009701 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009702 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009703 }
9704 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9705 }
9706 }
9707
Chris Lattner90ac28c2002-08-02 19:29:35 +00009708 // Combine Indices - If the source pointer to this getelementptr instruction
9709 // is a getelementptr instruction, combine the indices of the two
9710 // getelementptr instructions into a single instruction.
9711 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009712 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009713 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009714 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009715
9716 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009717 // Note that if our source is a gep chain itself that we wait for that
9718 // chain to be resolved before we perform this transformation. This
9719 // avoids us creating a TON of code in some cases.
9720 //
9721 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9722 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9723 return 0; // Wait until our source is folded to completion.
9724
Chris Lattner72588fc2007-02-15 22:48:32 +00009725 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009726
9727 // Find out whether the last index in the source GEP is a sequential idx.
9728 bool EndsWithSequential = false;
9729 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9730 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009731 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009732
Chris Lattner90ac28c2002-08-02 19:29:35 +00009733 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009734 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009735 // Replace: gep (gep %P, long B), long A, ...
9736 // With: T = long A+B; gep %P, T, ...
9737 //
Chris Lattner620ce142004-05-07 22:09:22 +00009738 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009739 if (SO1 == Constant::getNullValue(SO1->getType())) {
9740 Sum = GO1;
9741 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9742 Sum = SO1;
9743 } else {
9744 // If they aren't the same type, convert both to an integer of the
9745 // target's pointer size.
9746 if (SO1->getType() != GO1->getType()) {
9747 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009748 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009749 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009750 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009751 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009752 unsigned PS = TD->getPointerSizeInBits();
9753 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009754 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009755 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009756
Duncan Sands514ab342007-11-01 20:53:16 +00009757 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009758 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009759 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009760 } else {
9761 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009762 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9763 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009764 }
9765 }
9766 }
Chris Lattner620ce142004-05-07 22:09:22 +00009767 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9768 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9769 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009770 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009771 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009772 }
Chris Lattner28977af2004-04-05 01:30:19 +00009773 }
Chris Lattner620ce142004-05-07 22:09:22 +00009774
9775 // Recycle the GEP we already have if possible.
9776 if (SrcGEPOperands.size() == 2) {
9777 GEP.setOperand(0, SrcGEPOperands[0]);
9778 GEP.setOperand(1, Sum);
9779 return &GEP;
9780 } else {
9781 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9782 SrcGEPOperands.end()-1);
9783 Indices.push_back(Sum);
9784 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9785 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009786 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009787 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009788 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009789 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009790 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9791 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009792 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9793 }
9794
9795 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009796 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9797 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009798
Chris Lattner620ce142004-05-07 22:09:22 +00009799 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009800 // GEP of global variable. If all of the indices for this GEP are
9801 // constants, we can promote this to a constexpr instead of an instruction.
9802
9803 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009804 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009805 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9806 for (; I != E && isa<Constant>(*I); ++I)
9807 Indices.push_back(cast<Constant>(*I));
9808
9809 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009810 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9811 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009812
9813 // Replace all uses of the GEP with the new constexpr...
9814 return ReplaceInstUsesWith(GEP, CE);
9815 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009816 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009817 if (!isa<PointerType>(X->getType())) {
9818 // Not interesting. Source pointer must be a cast from pointer.
9819 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009820 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9821 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009822 //
9823 // This occurs when the program declares an array extern like "int X[];"
9824 //
9825 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9826 const PointerType *XTy = cast<PointerType>(X->getType());
9827 if (const ArrayType *XATy =
9828 dyn_cast<ArrayType>(XTy->getElementType()))
9829 if (const ArrayType *CATy =
9830 dyn_cast<ArrayType>(CPTy->getElementType()))
9831 if (CATy->getElementType() == XATy->getElementType()) {
9832 // At this point, we know that the cast source type is a pointer
9833 // to an array of the same type as the destination pointer
9834 // array. Because the array type is never stepped over (there
9835 // is a leading zero) we can fold the cast into this GEP.
9836 GEP.setOperand(0, X);
9837 return &GEP;
9838 }
9839 } else if (GEP.getNumOperands() == 2) {
9840 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009841 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9842 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009843 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9844 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9845 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009846 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9847 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009848 Value *Idx[2];
9849 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9850 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009851 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009852 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009853 // V and GEP are both pointer types --> BitCast
9854 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009855 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009856
9857 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009858 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009859 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009860 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009861
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009862 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009863 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009864 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009865
9866 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9867 // allow either a mul, shift, or constant here.
9868 Value *NewIdx = 0;
9869 ConstantInt *Scale = 0;
9870 if (ArrayEltSize == 1) {
9871 NewIdx = GEP.getOperand(1);
9872 Scale = ConstantInt::get(NewIdx->getType(), 1);
9873 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009874 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009875 Scale = CI;
9876 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9877 if (Inst->getOpcode() == Instruction::Shl &&
9878 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009879 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9880 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9881 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009882 NewIdx = Inst->getOperand(0);
9883 } else if (Inst->getOpcode() == Instruction::Mul &&
9884 isa<ConstantInt>(Inst->getOperand(1))) {
9885 Scale = cast<ConstantInt>(Inst->getOperand(1));
9886 NewIdx = Inst->getOperand(0);
9887 }
9888 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009889
Chris Lattner7835cdd2005-09-13 18:36:04 +00009890 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009891 // out, perform the transformation. Note, we don't know whether Scale is
9892 // signed or not. We'll use unsigned version of division/modulo
9893 // operation after making sure Scale doesn't have the sign bit set.
9894 if (Scale && Scale->getSExtValue() >= 0LL &&
9895 Scale->getZExtValue() % ArrayEltSize == 0) {
9896 Scale = ConstantInt::get(Scale->getType(),
9897 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009898 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009899 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009900 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009901 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009902 NewIdx = InsertNewInstBefore(Sc, GEP);
9903 }
9904
9905 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009906 Value *Idx[2];
9907 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9908 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009909 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009910 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009911 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9912 // The NewGEP must be pointer typed, so must the old one -> BitCast
9913 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009914 }
9915 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009916 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009917 }
9918
Chris Lattner8a2a3112001-12-14 16:52:21 +00009919 return 0;
9920}
9921
Chris Lattner0864acf2002-11-04 16:18:53 +00009922Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9923 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009924 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009925 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9926 const Type *NewTy =
9927 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009928 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009929
9930 // Create and insert the replacement instruction...
9931 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009932 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009933 else {
9934 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009935 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009936 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009937
9938 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009939
Chris Lattner0864acf2002-11-04 16:18:53 +00009940 // Scan to the end of the allocation instructions, to skip over a block of
9941 // allocas if possible...
9942 //
9943 BasicBlock::iterator It = New;
9944 while (isa<AllocationInst>(*It)) ++It;
9945
9946 // Now that I is pointing to the first non-allocation-inst in the block,
9947 // insert our getelementptr instruction...
9948 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009949 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009950 Value *Idx[2];
9951 Idx[0] = NullIdx;
9952 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009953 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9954 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009955
9956 // Now make everything use the getelementptr instead of the original
9957 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009958 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009959 } else if (isa<UndefValue>(AI.getArraySize())) {
9960 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009961 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009962 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009963
9964 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9965 // Note that we only do this for alloca's, because malloc should allocate and
9966 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009967 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009968 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009969 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9970
Chris Lattner0864acf2002-11-04 16:18:53 +00009971 return 0;
9972}
9973
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009974Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9975 Value *Op = FI.getOperand(0);
9976
Chris Lattner17be6352004-10-18 02:59:09 +00009977 // free undef -> unreachable.
9978 if (isa<UndefValue>(Op)) {
9979 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009980 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009981 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009982 return EraseInstFromFunction(FI);
9983 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009984
Chris Lattner6160e852004-02-28 04:57:37 +00009985 // If we have 'free null' delete the instruction. This can happen in stl code
9986 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009987 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009988 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009989
9990 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9991 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9992 FI.setOperand(0, CI->getOperand(0));
9993 return &FI;
9994 }
9995
9996 // Change free (gep X, 0,0,0,0) into free(X)
9997 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9998 if (GEPI->hasAllZeroIndices()) {
9999 AddToWorkList(GEPI);
10000 FI.setOperand(0, GEPI->getOperand(0));
10001 return &FI;
10002 }
10003 }
10004
10005 // Change free(malloc) into nothing, if the malloc has a single use.
10006 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10007 if (MI->hasOneUse()) {
10008 EraseInstFromFunction(FI);
10009 return EraseInstFromFunction(*MI);
10010 }
Chris Lattner6160e852004-02-28 04:57:37 +000010011
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010012 return 0;
10013}
10014
10015
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010016/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010017static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010018 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010019 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010020 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010021
Devang Patel99db6ad2007-10-18 19:52:32 +000010022 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10023 // Instead of loading constant c string, use corresponding integer value
10024 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010025 std::string Str;
10026 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010027 unsigned len = Str.length();
10028 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10029 unsigned numBits = Ty->getPrimitiveSizeInBits();
10030 // Replace LI with immediate integer store.
10031 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010032 APInt StrVal(numBits, 0);
10033 APInt SingleChar(numBits, 0);
10034 if (TD->isLittleEndian()) {
10035 for (signed i = len-1; i >= 0; i--) {
10036 SingleChar = (uint64_t) Str[i];
10037 StrVal = (StrVal << 8) | SingleChar;
10038 }
10039 } else {
10040 for (unsigned i = 0; i < len; i++) {
10041 SingleChar = (uint64_t) Str[i];
10042 StrVal = (StrVal << 8) | SingleChar;
10043 }
10044 // Append NULL at the end.
10045 SingleChar = 0;
10046 StrVal = (StrVal << 8) | SingleChar;
10047 }
10048 Value *NL = ConstantInt::get(StrVal);
10049 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010050 }
10051 }
10052 }
10053
Chris Lattnerb89e0712004-07-13 01:49:43 +000010054 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010055 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010056 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010057
Reid Spencer42230162007-01-22 05:51:25 +000010058 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010059 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010060 // If the source is an array, the code below will not succeed. Check to
10061 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10062 // constants.
10063 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10064 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10065 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010066 Value *Idxs[2];
10067 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10068 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010069 SrcTy = cast<PointerType>(CastOp->getType());
10070 SrcPTy = SrcTy->getElementType();
10071 }
10072
Reid Spencer42230162007-01-22 05:51:25 +000010073 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010074 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010075 // Do not allow turning this into a load of an integer, which is then
10076 // casted to a pointer, this pessimizes pointer analysis a lot.
10077 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010078 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10079 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010080
Chris Lattnerf9527852005-01-31 04:50:46 +000010081 // Okay, we are casting from one integer or pointer type to another of
10082 // the same size. Instead of casting the pointer before the load, cast
10083 // the result of the loaded value.
10084 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10085 CI->getName(),
10086 LI.isVolatile()),LI);
10087 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010088 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010089 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010090 }
10091 }
10092 return 0;
10093}
10094
Chris Lattnerc10aced2004-09-19 18:43:46 +000010095/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010096/// from this value cannot trap. If it is not obviously safe to load from the
10097/// specified pointer, we do a quick local scan of the basic block containing
10098/// ScanFrom, to determine if the address is already accessed.
10099static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010100 // If it is an alloca it is always safe to load from.
10101 if (isa<AllocaInst>(V)) return true;
10102
Duncan Sands46318cd2007-09-19 10:25:38 +000010103 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010104 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010105 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010106 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010107
10108 // Otherwise, be a little bit agressive by scanning the local block where we
10109 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010110 // from/to. If so, the previous load or store would have already trapped,
10111 // so there is no harm doing an extra load (also, CSE will later eliminate
10112 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010113 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10114
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010115 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010116 --BBI;
10117
Chris Lattner2de3fec2008-06-20 05:12:56 +000010118 // If we see a free or a call (which might do a free) the pointer could be
10119 // marked invalid.
10120 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10121 return false;
10122
Chris Lattner8a375202004-09-19 19:18:10 +000010123 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10124 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010125 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000010126 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010127 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010128
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010129 }
Chris Lattner8a375202004-09-19 19:18:10 +000010130 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010131}
10132
Chris Lattner8d2e8882007-08-11 18:48:48 +000010133/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10134/// until we find the underlying object a pointer is referring to or something
10135/// we don't understand. Note that the returned pointer may be offset from the
10136/// input, because we ignore GEP indices.
10137static Value *GetUnderlyingObject(Value *Ptr) {
10138 while (1) {
10139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10140 if (CE->getOpcode() == Instruction::BitCast ||
10141 CE->getOpcode() == Instruction::GetElementPtr)
10142 Ptr = CE->getOperand(0);
10143 else
10144 return Ptr;
10145 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10146 Ptr = BCI->getOperand(0);
10147 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10148 Ptr = GEP->getOperand(0);
10149 } else {
10150 return Ptr;
10151 }
10152 }
10153}
10154
Chris Lattner833b8a42003-06-26 05:06:25 +000010155Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10156 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010157
Dan Gohman9941f742007-07-20 16:34:21 +000010158 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010159 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10160 if (KnownAlign >
10161 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10162 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010163 LI.setAlignment(KnownAlign);
10164
Chris Lattner37366c12005-05-01 04:24:53 +000010165 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010166 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010167 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010168 return Res;
10169
10170 // None of the following transforms are legal for volatile loads.
10171 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010172
Chris Lattner62f254d2005-09-12 22:00:15 +000010173 if (&LI.getParent()->front() != &LI) {
10174 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010175 // If the instruction immediately before this is a store to the same
10176 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010177 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10178 if (SI->getOperand(1) == LI.getOperand(0))
10179 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010180 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10181 if (LIB->getOperand(0) == LI.getOperand(0))
10182 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010183 }
Chris Lattner37366c12005-05-01 04:24:53 +000010184
Christopher Lambb15147e2007-12-29 07:56:53 +000010185 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10186 const Value *GEPI0 = GEPI->getOperand(0);
10187 // TODO: Consider a target hook for valid address spaces for this xform.
10188 if (isa<ConstantPointerNull>(GEPI0) &&
10189 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010190 // Insert a new store to null instruction before the load to indicate
10191 // that this code is not reachable. We do this instead of inserting
10192 // an unreachable instruction directly because we cannot modify the
10193 // CFG.
10194 new StoreInst(UndefValue::get(LI.getType()),
10195 Constant::getNullValue(Op->getType()), &LI);
10196 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10197 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010198 }
Chris Lattner37366c12005-05-01 04:24:53 +000010199
Chris Lattnere87597f2004-10-16 18:11:37 +000010200 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010201 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010202 // TODO: Consider a target hook for valid address spaces for this xform.
10203 if (isa<UndefValue>(C) || (C->isNullValue() &&
10204 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010205 // Insert a new store to null instruction before the load to indicate that
10206 // this code is not reachable. We do this instead of inserting an
10207 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010208 new StoreInst(UndefValue::get(LI.getType()),
10209 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010210 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010211 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010212
Chris Lattnere87597f2004-10-16 18:11:37 +000010213 // Instcombine load (constant global) into the value loaded.
10214 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010215 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010216 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010217
Chris Lattnere87597f2004-10-16 18:11:37 +000010218 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010219 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010220 if (CE->getOpcode() == Instruction::GetElementPtr) {
10221 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010222 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010223 if (Constant *V =
10224 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010225 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010226 if (CE->getOperand(0)->isNullValue()) {
10227 // Insert a new store to null instruction before the load to indicate
10228 // that this code is not reachable. We do this instead of inserting
10229 // an unreachable instruction directly because we cannot modify the
10230 // CFG.
10231 new StoreInst(UndefValue::get(LI.getType()),
10232 Constant::getNullValue(Op->getType()), &LI);
10233 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10234 }
10235
Reid Spencer3da59db2006-11-27 01:05:10 +000010236 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010237 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010238 return Res;
10239 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010240 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010241 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010242
10243 // If this load comes from anywhere in a constant global, and if the global
10244 // is all undef or zero, we know what it loads.
10245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10246 if (GV->isConstant() && GV->hasInitializer()) {
10247 if (GV->getInitializer()->isNullValue())
10248 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10249 else if (isa<UndefValue>(GV->getInitializer()))
10250 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10251 }
10252 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010253
Chris Lattner37366c12005-05-01 04:24:53 +000010254 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010255 // Change select and PHI nodes to select values instead of addresses: this
10256 // helps alias analysis out a lot, allows many others simplifications, and
10257 // exposes redundancy in the code.
10258 //
10259 // Note that we cannot do the transformation unless we know that the
10260 // introduced loads cannot trap! Something like this is valid as long as
10261 // the condition is always false: load (select bool %C, int* null, int* %G),
10262 // but it would not be valid if we transformed it to load from null
10263 // unconditionally.
10264 //
10265 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10266 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010267 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10268 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010269 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010270 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010271 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010272 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010273 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010274 }
10275
Chris Lattner684fe212004-09-23 15:46:00 +000010276 // load (select (cond, null, P)) -> load P
10277 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10278 if (C->isNullValue()) {
10279 LI.setOperand(0, SI->getOperand(2));
10280 return &LI;
10281 }
10282
10283 // load (select (cond, P, null)) -> load P
10284 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10285 if (C->isNullValue()) {
10286 LI.setOperand(0, SI->getOperand(1));
10287 return &LI;
10288 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010289 }
10290 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010291 return 0;
10292}
10293
Reid Spencer55af2b52007-01-19 21:20:31 +000010294/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010295/// when possible.
10296static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10297 User *CI = cast<User>(SI.getOperand(1));
10298 Value *CastOp = CI->getOperand(0);
10299
10300 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10301 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10302 const Type *SrcPTy = SrcTy->getElementType();
10303
Reid Spencer42230162007-01-22 05:51:25 +000010304 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010305 // If the source is an array, the code below will not succeed. Check to
10306 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10307 // constants.
10308 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10309 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10310 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010311 Value* Idxs[2];
10312 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10313 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010314 SrcTy = cast<PointerType>(CastOp->getType());
10315 SrcPTy = SrcTy->getElementType();
10316 }
10317
Reid Spencer67f827c2007-01-20 23:35:48 +000010318 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10319 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10320 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010321
10322 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010323 // the same size. Instead of casting the pointer before
10324 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010325 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010326 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010327 Instruction::CastOps opcode = Instruction::BitCast;
10328 const Type* CastSrcTy = SIOp0->getType();
10329 const Type* CastDstTy = SrcPTy;
10330 if (isa<PointerType>(CastDstTy)) {
10331 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010332 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010333 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010334 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010335 opcode = Instruction::PtrToInt;
10336 }
10337 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010338 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010339 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010340 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010341 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010342 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010343 return new StoreInst(NewCast, CastOp);
10344 }
10345 }
10346 }
10347 return 0;
10348}
10349
Chris Lattner2f503e62005-01-31 05:36:43 +000010350Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10351 Value *Val = SI.getOperand(0);
10352 Value *Ptr = SI.getOperand(1);
10353
10354 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010355 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010356 ++NumCombined;
10357 return 0;
10358 }
Chris Lattner836692d2007-01-15 06:51:56 +000010359
10360 // If the RHS is an alloca with a single use, zapify the store, making the
10361 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010362 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010363 if (isa<AllocaInst>(Ptr)) {
10364 EraseInstFromFunction(SI);
10365 ++NumCombined;
10366 return 0;
10367 }
10368
10369 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10370 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10371 GEP->getOperand(0)->hasOneUse()) {
10372 EraseInstFromFunction(SI);
10373 ++NumCombined;
10374 return 0;
10375 }
10376 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010377
Dan Gohman9941f742007-07-20 16:34:21 +000010378 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010379 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10380 if (KnownAlign >
10381 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10382 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010383 SI.setAlignment(KnownAlign);
10384
Chris Lattner9ca96412006-02-08 03:25:32 +000010385 // Do really simple DSE, to catch cases where there are several consequtive
10386 // stores to the same location, separated by a few arithmetic operations. This
10387 // situation often occurs with bitfield accesses.
10388 BasicBlock::iterator BBI = &SI;
10389 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10390 --ScanInsts) {
10391 --BBI;
10392
10393 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10394 // Prev store isn't volatile, and stores to the same location?
10395 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10396 ++NumDeadStore;
10397 ++BBI;
10398 EraseInstFromFunction(*PrevSI);
10399 continue;
10400 }
10401 break;
10402 }
10403
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010404 // If this is a load, we have to stop. However, if the loaded value is from
10405 // the pointer we're loading and is producing the pointer we're storing,
10406 // then *this* store is dead (X = load P; store X -> P).
10407 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010408 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010409 EraseInstFromFunction(SI);
10410 ++NumCombined;
10411 return 0;
10412 }
10413 // Otherwise, this is a load from some other location. Stores before it
10414 // may not be dead.
10415 break;
10416 }
10417
Chris Lattner9ca96412006-02-08 03:25:32 +000010418 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010419 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010420 break;
10421 }
10422
10423
10424 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010425
10426 // store X, null -> turns into 'unreachable' in SimplifyCFG
10427 if (isa<ConstantPointerNull>(Ptr)) {
10428 if (!isa<UndefValue>(Val)) {
10429 SI.setOperand(0, UndefValue::get(Val->getType()));
10430 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010431 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010432 ++NumCombined;
10433 }
10434 return 0; // Do not modify these!
10435 }
10436
10437 // store undef, Ptr -> noop
10438 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010439 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010440 ++NumCombined;
10441 return 0;
10442 }
10443
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010444 // If the pointer destination is a cast, see if we can fold the cast into the
10445 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010446 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010447 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10448 return Res;
10449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010450 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010451 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10452 return Res;
10453
Chris Lattner408902b2005-09-12 23:23:25 +000010454
10455 // If this store is the last instruction in the basic block, and if the block
10456 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010457 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010458 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010459 if (BI->isUnconditional())
10460 if (SimplifyStoreAtEndOfBlock(SI))
10461 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010462
Chris Lattner2f503e62005-01-31 05:36:43 +000010463 return 0;
10464}
10465
Chris Lattner3284d1f2007-04-15 00:07:55 +000010466/// SimplifyStoreAtEndOfBlock - Turn things like:
10467/// if () { *P = v1; } else { *P = v2 }
10468/// into a phi node with a store in the successor.
10469///
Chris Lattner31755a02007-04-15 01:02:18 +000010470/// Simplify things like:
10471/// *P = v1; if () { *P = v2; }
10472/// into a phi node with a store in the successor.
10473///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010474bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10475 BasicBlock *StoreBB = SI.getParent();
10476
10477 // Check to see if the successor block has exactly two incoming edges. If
10478 // so, see if the other predecessor contains a store to the same location.
10479 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010480 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010481
10482 // Determine whether Dest has exactly two predecessors and, if so, compute
10483 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010484 pred_iterator PI = pred_begin(DestBB);
10485 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010486 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010487 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010488 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010489 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010490 return false;
10491
10492 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010493 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010494 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010495 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010496 }
Chris Lattner31755a02007-04-15 01:02:18 +000010497 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010498 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010499
10500 // Bail out if all the relevant blocks aren't distinct (this can happen,
10501 // for example, if SI is in an infinite loop)
10502 if (StoreBB == DestBB || OtherBB == DestBB)
10503 return false;
10504
Chris Lattner31755a02007-04-15 01:02:18 +000010505 // Verify that the other block ends in a branch and is not otherwise empty.
10506 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010507 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010508 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010509 return false;
10510
Chris Lattner31755a02007-04-15 01:02:18 +000010511 // If the other block ends in an unconditional branch, check for the 'if then
10512 // else' case. there is an instruction before the branch.
10513 StoreInst *OtherStore = 0;
10514 if (OtherBr->isUnconditional()) {
10515 // If this isn't a store, or isn't a store to the same location, bail out.
10516 --BBI;
10517 OtherStore = dyn_cast<StoreInst>(BBI);
10518 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10519 return false;
10520 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010521 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010522 // destinations is StoreBB, then we have the if/then case.
10523 if (OtherBr->getSuccessor(0) != StoreBB &&
10524 OtherBr->getSuccessor(1) != StoreBB)
10525 return false;
10526
10527 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010528 // if/then triangle. See if there is a store to the same ptr as SI that
10529 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010530 for (;; --BBI) {
10531 // Check to see if we find the matching store.
10532 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10533 if (OtherStore->getOperand(1) != SI.getOperand(1))
10534 return false;
10535 break;
10536 }
Eli Friedman6903a242008-06-13 22:02:12 +000010537 // If we find something that may be using or overwriting the stored
10538 // value, or if we run out of instructions, we can't do the xform.
10539 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010540 BBI == OtherBB->begin())
10541 return false;
10542 }
10543
10544 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010545 // make sure nothing reads or overwrites the stored value in
10546 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010547 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10548 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010549 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010550 return false;
10551 }
10552 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010553
Chris Lattner31755a02007-04-15 01:02:18 +000010554 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010555 Value *MergedVal = OtherStore->getOperand(0);
10556 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010557 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010558 PN->reserveOperandSpace(2);
10559 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010560 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10561 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010562 }
10563
10564 // Advance to a place where it is safe to insert the new store and
10565 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010566 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010567 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10568 OtherStore->isVolatile()), *BBI);
10569
10570 // Nuke the old stores.
10571 EraseInstFromFunction(SI);
10572 EraseInstFromFunction(*OtherStore);
10573 ++NumCombined;
10574 return true;
10575}
10576
Chris Lattner2f503e62005-01-31 05:36:43 +000010577
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010578Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10579 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010580 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010581 BasicBlock *TrueDest;
10582 BasicBlock *FalseDest;
10583 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10584 !isa<Constant>(X)) {
10585 // Swap Destinations and condition...
10586 BI.setCondition(X);
10587 BI.setSuccessor(0, FalseDest);
10588 BI.setSuccessor(1, TrueDest);
10589 return &BI;
10590 }
10591
Reid Spencere4d87aa2006-12-23 06:05:41 +000010592 // Cannonicalize fcmp_one -> fcmp_oeq
10593 FCmpInst::Predicate FPred; Value *Y;
10594 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10595 TrueDest, FalseDest)))
10596 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10597 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10598 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010599 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010600 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10601 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010602 // Swap Destinations and condition...
10603 BI.setCondition(NewSCC);
10604 BI.setSuccessor(0, FalseDest);
10605 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010606 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010607 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010608 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010609 return &BI;
10610 }
10611
10612 // Cannonicalize icmp_ne -> icmp_eq
10613 ICmpInst::Predicate IPred;
10614 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10615 TrueDest, FalseDest)))
10616 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10617 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10618 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10619 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010620 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010621 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10622 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010623 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010624 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010625 BI.setSuccessor(0, FalseDest);
10626 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010627 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010628 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010629 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010630 return &BI;
10631 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010632
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010633 return 0;
10634}
Chris Lattner0864acf2002-11-04 16:18:53 +000010635
Chris Lattner46238a62004-07-03 00:26:11 +000010636Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10637 Value *Cond = SI.getCondition();
10638 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10639 if (I->getOpcode() == Instruction::Add)
10640 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10641 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10642 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010643 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010644 AddRHS));
10645 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010646 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010647 return &SI;
10648 }
10649 }
10650 return 0;
10651}
10652
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010653Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010654 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010655
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000010656 if (!EV.hasIndices())
10657 return ReplaceInstUsesWith(EV, Agg);
10658
10659 if (Constant *C = dyn_cast<Constant>(Agg)) {
10660 if (isa<UndefValue>(C))
10661 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10662
10663 if (isa<ConstantAggregateZero>(C))
10664 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10665
10666 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10667 // Extract the element indexed by the first index out of the constant
10668 Value *V = C->getOperand(*EV.idx_begin());
10669 if (EV.getNumIndices() > 1)
10670 // Extract the remaining indices out of the constant indexed by the
10671 // first index
10672 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10673 else
10674 return ReplaceInstUsesWith(EV, V);
10675 }
10676 return 0; // Can't handle other constants
10677 }
10678 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10679 // We're extracting from an insertvalue instruction, compare the indices
10680 const unsigned *exti, *exte, *insi, *inse;
10681 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10682 exte = EV.idx_end(), inse = IV->idx_end();
10683 exti != exte && insi != inse;
10684 ++exti, ++insi) {
10685 if (*insi != *exti)
10686 // The insert and extract both reference distinctly different elements.
10687 // This means the extract is not influenced by the insert, and we can
10688 // replace the aggregate operand of the extract with the aggregate
10689 // operand of the insert. i.e., replace
10690 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10691 // %E = extractvalue { i32, { i32 } } %I, 0
10692 // with
10693 // %E = extractvalue { i32, { i32 } } %A, 0
10694 return ExtractValueInst::Create(IV->getAggregateOperand(),
10695 EV.idx_begin(), EV.idx_end());
10696 }
10697 if (exti == exte && insi == inse)
10698 // Both iterators are at the end: Index lists are identical. Replace
10699 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10700 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10701 // with "i32 42"
10702 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10703 if (exti == exte) {
10704 // The extract list is a prefix of the insert list. i.e. replace
10705 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10706 // %E = extractvalue { i32, { i32 } } %I, 1
10707 // with
10708 // %X = extractvalue { i32, { i32 } } %A, 1
10709 // %E = insertvalue { i32 } %X, i32 42, 0
10710 // by switching the order of the insert and extract (though the
10711 // insertvalue should be left in, since it may have other uses).
10712 Value *NewEV = InsertNewInstBefore(
10713 ExtractValueInst::Create(IV->getAggregateOperand(),
10714 EV.idx_begin(), EV.idx_end()),
10715 EV);
10716 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10717 insi, inse);
10718 }
10719 if (insi == inse)
10720 // The insert list is a prefix of the extract list
10721 // We can simply remove the common indices from the extract and make it
10722 // operate on the inserted value instead of the insertvalue result.
10723 // i.e., replace
10724 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10725 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10726 // with
10727 // %E extractvalue { i32 } { i32 42 }, 0
10728 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10729 exti, exte);
10730 }
10731 // Can't simplify extracts from other values. Note that nested extracts are
10732 // already simplified implicitely by the above (extract ( extract (insert) )
10733 // will be translated into extract ( insert ( extract ) ) first and then just
10734 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010735 return 0;
10736}
10737
Chris Lattner220b0cf2006-03-05 00:22:33 +000010738/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10739/// is to leave as a vector operation.
10740static bool CheapToScalarize(Value *V, bool isConstant) {
10741 if (isa<ConstantAggregateZero>(V))
10742 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010743 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010744 if (isConstant) return true;
10745 // If all elts are the same, we can extract.
10746 Constant *Op0 = C->getOperand(0);
10747 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10748 if (C->getOperand(i) != Op0)
10749 return false;
10750 return true;
10751 }
10752 Instruction *I = dyn_cast<Instruction>(V);
10753 if (!I) return false;
10754
10755 // Insert element gets simplified to the inserted element or is deleted if
10756 // this is constant idx extract element and its a constant idx insertelt.
10757 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10758 isa<ConstantInt>(I->getOperand(2)))
10759 return true;
10760 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10761 return true;
10762 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10763 if (BO->hasOneUse() &&
10764 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10765 CheapToScalarize(BO->getOperand(1), isConstant)))
10766 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010767 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10768 if (CI->hasOneUse() &&
10769 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10770 CheapToScalarize(CI->getOperand(1), isConstant)))
10771 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010772
10773 return false;
10774}
10775
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010776/// Read and decode a shufflevector mask.
10777///
10778/// It turns undef elements into values that are larger than the number of
10779/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010780static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10781 unsigned NElts = SVI->getType()->getNumElements();
10782 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10783 return std::vector<unsigned>(NElts, 0);
10784 if (isa<UndefValue>(SVI->getOperand(2)))
10785 return std::vector<unsigned>(NElts, 2*NElts);
10786
10787 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010788 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010789 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10790 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010791 Result.push_back(NElts*2); // undef -> 8
10792 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010793 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010794 return Result;
10795}
10796
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010797/// FindScalarElement - Given a vector and an element number, see if the scalar
10798/// value is already around as a register, for example if it were inserted then
10799/// extracted from the vector.
10800static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010801 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10802 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010803 unsigned Width = PTy->getNumElements();
10804 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010805 return UndefValue::get(PTy->getElementType());
10806
10807 if (isa<UndefValue>(V))
10808 return UndefValue::get(PTy->getElementType());
10809 else if (isa<ConstantAggregateZero>(V))
10810 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010811 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010812 return CP->getOperand(EltNo);
10813 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10814 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010815 if (!isa<ConstantInt>(III->getOperand(2)))
10816 return 0;
10817 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010818
10819 // If this is an insert to the element we are looking for, return the
10820 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010821 if (EltNo == IIElt)
10822 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010823
10824 // Otherwise, the insertelement doesn't modify the value, recurse on its
10825 // vector input.
10826 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010827 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010828 unsigned InEl = getShuffleMask(SVI)[EltNo];
10829 if (InEl < Width)
10830 return FindScalarElement(SVI->getOperand(0), InEl);
10831 else if (InEl < Width*2)
10832 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10833 else
10834 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010835 }
10836
10837 // Otherwise, we don't know.
10838 return 0;
10839}
10840
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010841Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010842 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010843 if (isa<UndefValue>(EI.getOperand(0)))
10844 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10845
Dan Gohman07a96762007-07-16 14:29:03 +000010846 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010847 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10848 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10849
Reid Spencer9d6565a2007-02-15 02:26:10 +000010850 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010851 // If vector val is constant with all elements the same, replace EI with
10852 // that element. When the elements are not identical, we cannot replace yet
10853 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010854 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010855 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010856 if (C->getOperand(i) != op0) {
10857 op0 = 0;
10858 break;
10859 }
10860 if (op0)
10861 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010862 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010863
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010864 // If extracting a specified index from the vector, see if we can recursively
10865 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010866 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010867 unsigned IndexVal = IdxC->getZExtValue();
10868 unsigned VectorWidth =
10869 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10870
10871 // If this is extracting an invalid index, turn this into undef, to avoid
10872 // crashing the code below.
10873 if (IndexVal >= VectorWidth)
10874 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10875
Chris Lattner867b99f2006-10-05 06:55:50 +000010876 // This instruction only demands the single element from the input vector.
10877 // If the input vector has a single use, simplify it based on this use
10878 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010879 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010880 uint64_t UndefElts;
10881 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010882 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010883 UndefElts)) {
10884 EI.setOperand(0, V);
10885 return &EI;
10886 }
10887 }
10888
Reid Spencerb83eb642006-10-20 07:07:24 +000010889 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010890 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010891
10892 // If the this extractelement is directly using a bitcast from a vector of
10893 // the same number of elements, see if we can find the source element from
10894 // it. In this case, we will end up needing to bitcast the scalars.
10895 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10896 if (const VectorType *VT =
10897 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10898 if (VT->getNumElements() == VectorWidth)
10899 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10900 return new BitCastInst(Elt, EI.getType());
10901 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010902 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010903
Chris Lattner73fa49d2006-05-25 22:53:38 +000010904 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010905 if (I->hasOneUse()) {
10906 // Push extractelement into predecessor operation if legal and
10907 // profitable to do so
10908 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010909 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10910 if (CheapToScalarize(BO, isConstantElt)) {
10911 ExtractElementInst *newEI0 =
10912 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10913 EI.getName()+".lhs");
10914 ExtractElementInst *newEI1 =
10915 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10916 EI.getName()+".rhs");
10917 InsertNewInstBefore(newEI0, EI);
10918 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010919 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010920 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010921 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010922 unsigned AS =
10923 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010924 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10925 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010926 GetElementPtrInst *GEP =
10927 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010928 InsertNewInstBefore(GEP, EI);
10929 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010930 }
10931 }
10932 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10933 // Extracting the inserted element?
10934 if (IE->getOperand(2) == EI.getOperand(1))
10935 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10936 // If the inserted and extracted elements are constants, they must not
10937 // be the same value, extract from the pre-inserted value instead.
10938 if (isa<Constant>(IE->getOperand(2)) &&
10939 isa<Constant>(EI.getOperand(1))) {
10940 AddUsesToWorkList(EI);
10941 EI.setOperand(0, IE->getOperand(0));
10942 return &EI;
10943 }
10944 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10945 // If this is extracting an element from a shufflevector, figure out where
10946 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010947 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10948 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010949 Value *Src;
10950 if (SrcIdx < SVI->getType()->getNumElements())
10951 Src = SVI->getOperand(0);
10952 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10953 SrcIdx -= SVI->getType()->getNumElements();
10954 Src = SVI->getOperand(1);
10955 } else {
10956 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010957 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010958 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010959 }
10960 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010961 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010962 return 0;
10963}
10964
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010965/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10966/// elements from either LHS or RHS, return the shuffle mask and true.
10967/// Otherwise, return false.
10968static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10969 std::vector<Constant*> &Mask) {
10970 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10971 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010972 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010973
10974 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010975 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010976 return true;
10977 } else if (V == LHS) {
10978 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010979 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010980 return true;
10981 } else if (V == RHS) {
10982 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010983 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010984 return true;
10985 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10986 // If this is an insert of an extract from some other vector, include it.
10987 Value *VecOp = IEI->getOperand(0);
10988 Value *ScalarOp = IEI->getOperand(1);
10989 Value *IdxOp = IEI->getOperand(2);
10990
Chris Lattnerd929f062006-04-27 21:14:21 +000010991 if (!isa<ConstantInt>(IdxOp))
10992 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010993 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010994
10995 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10996 // Okay, we can handle this if the vector we are insertinting into is
10997 // transitively ok.
10998 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10999 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011000 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011001 return true;
11002 }
11003 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11004 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011005 EI->getOperand(0)->getType() == V->getType()) {
11006 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011007 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011008
11009 // This must be extracting from either LHS or RHS.
11010 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11011 // Okay, we can handle this if the vector we are insertinting into is
11012 // transitively ok.
11013 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11014 // If so, update the mask to reflect the inserted value.
11015 if (EI->getOperand(0) == LHS) {
11016 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011017 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011018 } else {
11019 assert(EI->getOperand(0) == RHS);
11020 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011021 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011022
11023 }
11024 return true;
11025 }
11026 }
11027 }
11028 }
11029 }
11030 // TODO: Handle shufflevector here!
11031
11032 return false;
11033}
11034
11035/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11036/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11037/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011038static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011039 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011040 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011041 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011042 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011043 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011044
11045 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011046 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011047 return V;
11048 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011049 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011050 return V;
11051 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11052 // If this is an insert of an extract from some other vector, include it.
11053 Value *VecOp = IEI->getOperand(0);
11054 Value *ScalarOp = IEI->getOperand(1);
11055 Value *IdxOp = IEI->getOperand(2);
11056
11057 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11058 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11059 EI->getOperand(0)->getType() == V->getType()) {
11060 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011061 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11062 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011063
11064 // Either the extracted from or inserted into vector must be RHSVec,
11065 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011066 if (EI->getOperand(0) == RHS || RHS == 0) {
11067 RHS = EI->getOperand(0);
11068 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011069 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011070 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011071 return V;
11072 }
11073
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011074 if (VecOp == RHS) {
11075 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011076 // Everything but the extracted element is replaced with the RHS.
11077 for (unsigned i = 0; i != NumElts; ++i) {
11078 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011079 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011080 }
11081 return V;
11082 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011083
11084 // If this insertelement is a chain that comes from exactly these two
11085 // vectors, return the vector and the effective shuffle.
11086 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11087 return EI->getOperand(0);
11088
Chris Lattnerefb47352006-04-15 01:39:45 +000011089 }
11090 }
11091 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011092 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011093
11094 // Otherwise, can't do anything fancy. Return an identity vector.
11095 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011096 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011097 return V;
11098}
11099
11100Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11101 Value *VecOp = IE.getOperand(0);
11102 Value *ScalarOp = IE.getOperand(1);
11103 Value *IdxOp = IE.getOperand(2);
11104
Chris Lattner599ded12007-04-09 01:11:16 +000011105 // Inserting an undef or into an undefined place, remove this.
11106 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11107 ReplaceInstUsesWith(IE, VecOp);
11108
Chris Lattnerefb47352006-04-15 01:39:45 +000011109 // If the inserted element was extracted from some other vector, and if the
11110 // indexes are constant, try to turn this into a shufflevector operation.
11111 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11112 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11113 EI->getOperand(0)->getType() == IE.getType()) {
11114 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011115 unsigned ExtractedIdx =
11116 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011117 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011118
11119 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11120 return ReplaceInstUsesWith(IE, VecOp);
11121
11122 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11123 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11124
11125 // If we are extracting a value from a vector, then inserting it right
11126 // back into the same place, just use the input vector.
11127 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11128 return ReplaceInstUsesWith(IE, VecOp);
11129
11130 // We could theoretically do this for ANY input. However, doing so could
11131 // turn chains of insertelement instructions into a chain of shufflevector
11132 // instructions, and right now we do not merge shufflevectors. As such,
11133 // only do this in a situation where it is clear that there is benefit.
11134 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11135 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11136 // the values of VecOp, except then one read from EIOp0.
11137 // Build a new shuffle mask.
11138 std::vector<Constant*> Mask;
11139 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011140 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011141 else {
11142 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011143 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011144 NumVectorElts));
11145 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011146 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011147 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011148 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011149 }
11150
11151 // If this insertelement isn't used by some other insertelement, turn it
11152 // (and any insertelements it points to), into one big shuffle.
11153 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11154 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011155 Value *RHS = 0;
11156 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11157 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11158 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011159 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011160 }
11161 }
11162 }
11163
11164 return 0;
11165}
11166
11167
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011168Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11169 Value *LHS = SVI.getOperand(0);
11170 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011171 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011172
11173 bool MadeChange = false;
11174
Chris Lattner867b99f2006-10-05 06:55:50 +000011175 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011176 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011177 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11178
Chris Lattnere4929dd2007-01-05 07:36:08 +000011179 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011180 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011181 if (isa<UndefValue>(SVI.getOperand(1))) {
11182 // Scan to see if there are any references to the RHS. If so, replace them
11183 // with undef element refs and set MadeChange to true.
11184 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11185 if (Mask[i] >= e && Mask[i] != 2*e) {
11186 Mask[i] = 2*e;
11187 MadeChange = true;
11188 }
11189 }
11190
11191 if (MadeChange) {
11192 // Remap any references to RHS to use LHS.
11193 std::vector<Constant*> Elts;
11194 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11195 if (Mask[i] == 2*e)
11196 Elts.push_back(UndefValue::get(Type::Int32Ty));
11197 else
11198 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11199 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011200 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011201 }
11202 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011203
Chris Lattner863bcff2006-05-25 23:48:38 +000011204 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11205 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11206 if (LHS == RHS || isa<UndefValue>(LHS)) {
11207 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011208 // shuffle(undef,undef,mask) -> undef.
11209 return ReplaceInstUsesWith(SVI, LHS);
11210 }
11211
Chris Lattner863bcff2006-05-25 23:48:38 +000011212 // Remap any references to RHS to use LHS.
11213 std::vector<Constant*> Elts;
11214 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011215 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011216 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011217 else {
11218 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11219 (Mask[i] < e && isa<UndefValue>(LHS)))
11220 Mask[i] = 2*e; // Turn into undef.
11221 else
11222 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011223 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011224 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011225 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011226 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011227 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011228 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011229 LHS = SVI.getOperand(0);
11230 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011231 MadeChange = true;
11232 }
11233
Chris Lattner7b2e27922006-05-26 00:29:06 +000011234 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011235 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011236
Chris Lattner863bcff2006-05-25 23:48:38 +000011237 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11238 if (Mask[i] >= e*2) continue; // Ignore undef values.
11239 // Is this an identity shuffle of the LHS value?
11240 isLHSID &= (Mask[i] == i);
11241
11242 // Is this an identity shuffle of the RHS value?
11243 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011244 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011245
Chris Lattner863bcff2006-05-25 23:48:38 +000011246 // Eliminate identity shuffles.
11247 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11248 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011249
Chris Lattner7b2e27922006-05-26 00:29:06 +000011250 // If the LHS is a shufflevector itself, see if we can combine it with this
11251 // one without producing an unusual shuffle. Here we are really conservative:
11252 // we are absolutely afraid of producing a shuffle mask not in the input
11253 // program, because the code gen may not be smart enough to turn a merged
11254 // shuffle into two specific shuffles: it may produce worse code. As such,
11255 // we only merge two shuffles if the result is one of the two input shuffle
11256 // masks. In this case, merging the shuffles just removes one instruction,
11257 // which we know is safe. This is good for things like turning:
11258 // (splat(splat)) -> splat.
11259 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11260 if (isa<UndefValue>(RHS)) {
11261 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11262
11263 std::vector<unsigned> NewMask;
11264 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11265 if (Mask[i] >= 2*e)
11266 NewMask.push_back(2*e);
11267 else
11268 NewMask.push_back(LHSMask[Mask[i]]);
11269
11270 // If the result mask is equal to the src shuffle or this shuffle mask, do
11271 // the replacement.
11272 if (NewMask == LHSMask || NewMask == Mask) {
11273 std::vector<Constant*> Elts;
11274 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11275 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011276 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011277 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011278 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011279 }
11280 }
11281 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11282 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011283 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011284 }
11285 }
11286 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011287
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011288 return MadeChange ? &SVI : 0;
11289}
11290
11291
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011292
Chris Lattnerea1c4542004-12-08 23:43:58 +000011293
11294/// TryToSinkInstruction - Try to move the specified instruction from its
11295/// current block into the beginning of DestBlock, which can only happen if it's
11296/// safe to move the instruction past all of the instructions between it and the
11297/// end of its block.
11298static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11299 assert(I->hasOneUse() && "Invariants didn't hold!");
11300
Chris Lattner108e9022005-10-27 17:13:11 +000011301 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011302 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11303 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011304
Chris Lattnerea1c4542004-12-08 23:43:58 +000011305 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011306 if (isa<AllocaInst>(I) && I->getParent() ==
11307 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011308 return false;
11309
Chris Lattner96a52a62004-12-09 07:14:34 +000011310 // We can only sink load instructions if there is nothing between the load and
11311 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011312 if (I->mayReadFromMemory()) {
11313 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011314 Scan != E; ++Scan)
11315 if (Scan->mayWriteToMemory())
11316 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011317 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011318
Dan Gohman02dea8b2008-05-23 21:05:58 +000011319 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011320
Chris Lattner4bc5f802005-08-08 19:11:57 +000011321 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011322 ++NumSunkInst;
11323 return true;
11324}
11325
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011326
11327/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11328/// all reachable code to the worklist.
11329///
11330/// This has a couple of tricks to make the code faster and more powerful. In
11331/// particular, we constant fold and DCE instructions as we go, to avoid adding
11332/// them to the worklist (this significantly speeds up instcombine on code where
11333/// many instructions are dead or constant). Additionally, if we find a branch
11334/// whose condition is a known constant, we only visit the reachable successors.
11335///
11336static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011337 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011338 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011339 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011340 std::vector<BasicBlock*> Worklist;
11341 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011342
Chris Lattner2c7718a2007-03-23 19:17:18 +000011343 while (!Worklist.empty()) {
11344 BB = Worklist.back();
11345 Worklist.pop_back();
11346
11347 // We have now visited this block! If we've already been here, ignore it.
11348 if (!Visited.insert(BB)) continue;
11349
11350 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11351 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011352
Chris Lattner2c7718a2007-03-23 19:17:18 +000011353 // DCE instruction if trivially dead.
11354 if (isInstructionTriviallyDead(Inst)) {
11355 ++NumDeadInst;
11356 DOUT << "IC: DCE: " << *Inst;
11357 Inst->eraseFromParent();
11358 continue;
11359 }
11360
11361 // ConstantProp instruction if trivially constant.
11362 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11363 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11364 Inst->replaceAllUsesWith(C);
11365 ++NumConstProp;
11366 Inst->eraseFromParent();
11367 continue;
11368 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011369
Chris Lattner2c7718a2007-03-23 19:17:18 +000011370 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011371 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011372
11373 // Recursively visit successors. If this is a branch or switch on a
11374 // constant, only visit the reachable successor.
11375 TerminatorInst *TI = BB->getTerminator();
11376 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11377 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11378 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011379 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011380 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011381 continue;
11382 }
11383 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11384 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11385 // See if this is an explicit destination.
11386 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11387 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011388 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011389 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011390 continue;
11391 }
11392
11393 // Otherwise it is the default destination.
11394 Worklist.push_back(SI->getSuccessor(0));
11395 continue;
11396 }
11397 }
11398
11399 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11400 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011401 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011402}
11403
Chris Lattnerec9c3582007-03-03 02:04:50 +000011404bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011405 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011406 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011407
11408 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11409 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011410
Chris Lattnerb3d59702005-07-07 20:40:38 +000011411 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011412 // Do a depth-first traversal of the function, populate the worklist with
11413 // the reachable instructions. Ignore blocks that are not reachable. Keep
11414 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011415 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011416 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011417
Chris Lattnerb3d59702005-07-07 20:40:38 +000011418 // Do a quick scan over the function. If we find any blocks that are
11419 // unreachable, remove any instructions inside of them. This prevents
11420 // the instcombine code from having to deal with some bad special cases.
11421 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11422 if (!Visited.count(BB)) {
11423 Instruction *Term = BB->getTerminator();
11424 while (Term != BB->begin()) { // Remove instrs bottom-up
11425 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011426
Bill Wendlingb7427032006-11-26 09:46:52 +000011427 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011428 ++NumDeadInst;
11429
11430 if (!I->use_empty())
11431 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11432 I->eraseFromParent();
11433 }
11434 }
11435 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011436
Chris Lattnerdbab3862007-03-02 21:28:56 +000011437 while (!Worklist.empty()) {
11438 Instruction *I = RemoveOneFromWorkList();
11439 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011440
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011441 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011442 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011443 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011444 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011445 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011446 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011447
Bill Wendlingb7427032006-11-26 09:46:52 +000011448 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011449
11450 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011451 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011452 continue;
11453 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011454
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011455 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011456 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011457 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011458
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011459 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011460 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011461 ReplaceInstUsesWith(*I, C);
11462
Chris Lattner62b14df2002-09-02 04:59:56 +000011463 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011464 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011465 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011466 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011467 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011468
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011469 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11470 // See if we can constant fold its operands.
11471 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11473 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11474 i->set(NewC);
11475 }
11476 }
11477 }
11478
Chris Lattnerea1c4542004-12-08 23:43:58 +000011479 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000011480 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011481 BasicBlock *BB = I->getParent();
11482 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11483 if (UserParent != BB) {
11484 bool UserIsSuccessor = false;
11485 // See if the user is one of our successors.
11486 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11487 if (*SI == UserParent) {
11488 UserIsSuccessor = true;
11489 break;
11490 }
11491
11492 // If the user is one of our immediate successors, and if that successor
11493 // only has us as a predecessors (we'd have to split the critical edge
11494 // otherwise), we can keep going.
11495 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11496 next(pred_begin(UserParent)) == pred_end(UserParent))
11497 // Okay, the CFG is simple enough, try to sink this instruction.
11498 Changed |= TryToSinkInstruction(I, UserParent);
11499 }
11500 }
11501
Chris Lattner8a2a3112001-12-14 16:52:21 +000011502 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011503#ifndef NDEBUG
11504 std::string OrigI;
11505#endif
11506 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011507 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011508 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011509 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011510 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011511 DOUT << "IC: Old = " << *I
11512 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011513
Chris Lattnerf523d062004-06-09 05:08:07 +000011514 // Everything uses the new instruction now.
11515 I->replaceAllUsesWith(Result);
11516
11517 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011518 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011519 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011520
Chris Lattner6934a042007-02-11 01:23:03 +000011521 // Move the name to the new instruction first.
11522 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011523
11524 // Insert the new instruction into the basic block...
11525 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011526 BasicBlock::iterator InsertPos = I;
11527
11528 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11529 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11530 ++InsertPos;
11531
11532 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011533
Chris Lattner00d51312004-05-01 23:27:23 +000011534 // Make sure that we reprocess all operands now that we reduced their
11535 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011536 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011537
Chris Lattnerf523d062004-06-09 05:08:07 +000011538 // Instructions can end up on the worklist more than once. Make sure
11539 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011540 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011541
11542 // Erase the old instruction.
11543 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011544 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011545#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011546 DOUT << "IC: Mod = " << OrigI
11547 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011548#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011549
Chris Lattner90ac28c2002-08-02 19:29:35 +000011550 // If the instruction was modified, it's possible that it is now dead.
11551 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011552 if (isInstructionTriviallyDead(I)) {
11553 // Make sure we process all operands now that we are reducing their
11554 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011555 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011556
Chris Lattner00d51312004-05-01 23:27:23 +000011557 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011558 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011559 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011560 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011561 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011562 AddToWorkList(I);
11563 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011564 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011565 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011566 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011567 }
11568 }
11569
Chris Lattnerec9c3582007-03-03 02:04:50 +000011570 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011571
11572 // Do an explicit clear, this shrinks the map if needed.
11573 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011574 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011575}
11576
Chris Lattnerec9c3582007-03-03 02:04:50 +000011577
11578bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011579 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11580
Chris Lattnerec9c3582007-03-03 02:04:50 +000011581 bool EverMadeChange = false;
11582
11583 // Iterate while there is work to do.
11584 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011585 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011586 EverMadeChange = true;
11587 return EverMadeChange;
11588}
11589
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011590FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011591 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011592}
Brian Gaeked0fde302003-11-11 22:41:34 +000011593